A static library in C is a collection of object files that are linked into the program at compile-time. The final executable contains all the code from the static library, making it self-contained.
Write the Source Files:
.c
) and corresponding header files (.h
).Example:
// file: add.c
int add(int a, int b) {
return a + b;
}
// file: sub.c
int sub(int a, int b) {
return a - b;
}
// file: mathlib.h
int add(int a, int b);
int sub(int a, int b);
Compile the Source Files into Object Files:
Use the gcc
compiler to create .o
object files.
gcc -c add.c sub.c
c
: Tells gcc
to only compile the files to object files (add.o
, sub.o
), not linking them.Create the Static Library Archive:
Use the ar
(archive) command to bundle the object files into a static library (.a
file).
ar rcs libmathlib.a add.o sub.o
r
: Insert or replace object files in the library.c
: Create the library if it doesn’t exist.s
: Index the object files for faster access.Use the Static Library in a Program: To use the static library in a program, link it during the compilation of the main program.
Example:
// file: main.c
#include "mathlib.h"
#include <stdio.h>
int main() {
printf("Sum: %d\\\\n", add(3, 4));
printf("Difference: %d\\\\n", sub(10, 5));
return 0;
}
Compile and link the program with the static library:
gcc main.c -L. -lmathlib -o main
L.
: Specifies the directory containing the static library.lmathlib
: Links the libmathlib.a
library.o main
: Generates the final executable.Run the Program: After compiling and linking, run the program:
./main
gcc -c
to compile source files into object files.ar rcs
to create the static library.gcc -L. -l
to link the static library to your program.