Linking with static libraries
What you'll learn: How to merge a pre-compiled library directly into your final executable to create a standalone program.
The "All-in-One" Suitcase
Imagine you are packing for a trip. You have two choices: you can bring a small bag and hope the hotel provides a hairdryer and shampoo (Dynamic Linking), or you can pack everything you could possibly need directly into your suitcase (Static Linking).
A static library (usually ending in .a on Linux or .lib on Windows) is like that overpacked suitcase. It is a collection of pre-compiled object files bundled together. When you link a static library to your program, the linker copies the actual code from the library and pastes it right into your final executable file.
Why use Static Libraries?
Because the library code becomes part of your program's binary, the user doesn't need to have any special files installed on their system to run your app. It is "self-contained." The downside? Your program’s file size will be larger, and if the library gets a security update, you have to re-compile your entire program to include the fix.
How to Link It
To use a static library, you first need the header file (to tell the compiler what functions look like) and the library file itself (the actual compiled code).
If you have a library called libmathutils.a, you tell your compiler where to find it and to include it during the final build phase:
// main.c
#include <stdio.h>
#include "mathutils.h" // The header for our library
int main() {
// add_numbers is defined inside libmathutils.a
int result = add_numbers(10, 20);
printf("Result: %d\n", result);
return 0;
}
To compile this on a terminal using gcc, you would run:
gcc main.c -L. -lmathutils -o my_program
-L.tells the compiler to look in the current folder for libraries.-lmathutilstells it to link the library (thelibprefix and.aextension are assumed).
The resulting my_program now contains a copy of add_numbers. You could delete libmathutils.a now, and your program would still run perfectly.
Key takeaway
Static linking copies the library code into your executable, making your program larger but completely self-reliant.