TExcelTAD
Home › Build Fundamentals: From Source to Binary › Static Libraries (ar)

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 running ranlib).
  • ar t lists the members. They are whole object files, so the archive keeps each .o exactly as compiled.
  • The archive index maps every global symbol to the member that defines it. The linker uses it to find power without opening every member.
  • The lib prefix and .a suffix are a convention that -l relies on: -lmymath searches each -L directory for libmymath.so, then libmymath.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 '^
  

 -e Discarded
./app
nm app | grep -E ' T (add|mul|power)
  

Archive member included to satisfy reference by file (symbol)
./libmymath.a(pow.o)          main.o (power)
./libmymath.a(mul.o)          ./libmymath.a(pow.o) (mul)
Merging program properties
As-needed library included to satisfy reference by file (symbol)
libc.so.6                     main.o (__printf_chk@@GLIBC_2.3.4)
2^10 = 1024
00000000000011ba T mul
0000000000001182 T power

The first section of the linker map lists every archive member that was taken and why: pow.o because main.o needs power, then mul.o because pow.o needs mul. The map also records that libc.so.6 was linked for __printf_chk: Ubuntu's GCC enables _FORTIFY_SOURCE when optimising, which turns printf into its bounds-checked variant. add.o was never needed, so add is not in the program. This is why libraries are often split into one function per source file: the granularity of static linking is the object file, not the function. (-ffunction-sections with -Wl,--gc-sections gets you per-function granularity instead.)

Pulling in everything: --whole-archive

Sometimes you want every member, even if nothing references it, for example plugins that register themselves from a constructor function. --whole-archive does that for the archives that follow it:

bash · try it yourself
mkdir -p reg && cd reg
cat > plugin_zip.c <<'SRC'
#include <stdio.h>
__attribute__((constructor)) static void reg(void) { puts("registered: zip"); }
SRC
cat > plugin_tar.c <<'SRC'
#include <stdio.h>
__attribute__((constructor)) static void reg(void) { puts("registered: tar"); }
SRC
printf '#include <stdio.h>\nint main(void) { puts("main runs"); return 0; }\n' > main.c
gcc -c plugin_tar.c plugin_zip.c main.c
ar rcs libplugins.a plugin_tar.o plugin_zip.o
echo "--- normal link"
gcc main.o -L. -lplugins -o app && ./app
echo "--- whole archive"
gcc main.o -Wl,--whole-archive -L. -lplugins -Wl,--no-whole-archive -o app && ./app
--- normal link
main runs
--- whole archive
registered: tar
registered: zip
main runs

Nothing references the plugin objects by name, so a normal link drops them and their constructors never run. This "self-registering objects disappear" bug is common when code moves from a list of .o files into a library. Always close with --no-whole-archive, or the C library's archives would be swallowed whole too.

Updating and deterministic archives

ar r replaces a member in place. On Ubuntu, ar runs in deterministic mode by default (D): it stores zero timestamps, user ids and group ids, so the same objects always give a byte-identical archive. That matters for Reproducible Builds:

bash · try it yourself
mkdir -p det && cd det
printf 'int one(void) { return 1; }\n' > one.c
gcc -c one.c
ar rcs liba.a one.o
sleep 1 && touch one.o
ar rcs libb.a one.o
cmp liba.a libb.a && echo "identical archives"
ar tv liba.a
ar rcsU libc-like.a one.o
cmp -s liba.a libc-like.a && echo "identical" || echo "U mode stores real timestamps and ids: different"
identical archives
rw-r--r-- 0/0   1224 Jan  1 00:00 1970 one.o
U mode stores real timestamps and ids: different

Model: archive index lookup

The linker's use of the index is a small fixed-point loop: look up each undefined symbol, add that member, add the member's own needs, repeat:

python · try it yourself
archive = {   # member -> (defines, needs)
    "add.o": ({"add"}, set()),
    "mul.o": ({"mul"}, set()),
    "pow.o": ({"power"}, {"mul"}),
    "log.o": ({"log_msg"}, {"printf"}),
}
index = {sym: member for member, (defs, _) in archive.items() for sym in defs}

undefined = {"power", "printf"}       # needed by main.o
taken = []
changed = True
while changed:
    changed = False
    for sym in sorted(undefined):
        member = index.get(sym)
        if member and member not in taken:
            taken.append(member)
            defs, needs = archive[member]
            undefined = (undefined - defs) | (needs - {s for m in taken for s in archive[m][0]})
            changed = True
            break
print("members taken:", taken)
print("still undefined (left for the next library):", sorted(undefined))
members taken: ['pow.o', 'mul.o']
still undefined (left for the next library): ['printf']

printf stays undefined: it is not in this archive, so it must come from a library later on the command line (here, the C library the driver adds at the end).

Test yourself

Which members of a static library end up in the executable?

  1. All of them
  2. Only the members that resolve an undefined symbol (and the members those need)
  3. Only the first member
  4. None, they are loaded at run time

What does the s in ar rcs do?

  1. Strips debug info
  2. Writes the symbol index, like ranlib
  3. Makes a shared library
  4. Sorts members

Why did the plugin constructors not run after a normal link with -lplugins?

  1. Constructors don't work in libraries
  2. Nothing referenced the plugin objects, so the linker never extracted them
  3. They need -fPIC
  4. The library was empty