Static Libraries (ar)
A static library is the simplest kind of library: an archive of object files, bundled with an index of the symbols they define. On Unix it is a .a file made by ar (on Windows, a .lib file). At link time the linker copies the members it needs into the executable, and the library is no longer needed afterwards.
Building and inspecting an archive
bash · try it yourself
mkdir -p mathlib && cd mathlib
cat > add.c <<'SRC'
int add(int a, int b) { return a + b; }
SRC
cat > mul.c <<'SRC'
int mul(int a, int b) { return a * b; }
SRC
cat > pow.c <<'SRC'
int mul(int a, int b);
int power(int base, int exp) {
int r = 1;
while (exp-- > 0) r = mul(r, base);
return r;
}
SRC
gcc -c -O1 add.c mul.c pow.c
ar rcs libmymath.a add.o mul.o pow.o
ar t libmymath.a
echo "--- index (nm -s)"
nm -s libmymath.a | sed -n '/Archive index/,/^$/p'add.o
mul.o
pow.o
--- index (nm -s)
Archive index:
add in add.o
mul in mul.o
power in pow.o
ar rcs: replace (or add) members, create the archive without complaining, write an index (s, the same as runningranlib).ar tlists the members. They are whole object files, so the archive keeps each.oexactly as compiled.- The archive index maps every global symbol to the member that defines it. The linker uses it to find
powerwithout opening every member. - The
libprefix and.asuffix are a convention that-lrelies on:-lmymathsearches each-Ldirectory forlibmymath.so, thenlibmymath.a.
Only what you use is linked
The linker pulls in a member only if it resolves an undefined symbol, and then follows the new member's own undefined symbols (pow.o needs mul):
bash · try it yourself
mkdir -p mathlib && cd mathlib
printf 'int add(int a, int b) { return a + b; }\n' > add.c
printf 'int mul(int a, int b) { return a * b; }\n' > mul.c
printf 'int mul(int, int);\nint power(int b, int e) { int r = 1; while (e-- > 0) r = mul(r, b); return r; }\n' > pow.c
gcc -c -O1 add.c mul.c pow.c
ar rcs libmymath.a add.o mul.o pow.o
cat > main.c <<'SRC'
#include <stdio.h>
int power(int base, int exp);
int main(void) { printf("2^10 = %d\n", power(2, 10)); return 0; }
SRC
gcc -O1 -c main.c
gcc main.o -L. -lmymath -o app -Wl,-Map=app.map
sed -n '/Archive member included/,/^Discarded/p' app.map | grep -v -e '^