Quiz Entry - updated: 2026.07.10
How do you create and use a static library (.a file)?
A .a file is just an archive of .o files built with ar; when you link against it, the linker pulls in only the objects needed to resolve undefined symbols.
* An archive is a bag of .o files; the linker extracts only the members that satisfy still-undefined symbols and drops the rest. *
# 1. Compile source files to objects
$ gcc -c addvec.c multvec.c
# 2. Create archive with ar
$ ar rcs libvector.a addvec.o multvec.o
# 3. Link against the library
$ gcc -o prog main.c -L. -lvector
# or
$ gcc -o prog main.c libvector.a
Archive flags:
r- insert/replace filesc- create archive if neededs- create index for faster linking
How the linker uses archives:
- Scans archive for object files
- Only includes objects that resolve undefined symbols
- Unused objects are not included
Order matters!
# WRONG: library before files that need it
# Symbols not found!
$ gcc -lvector main.c
# RIGHT: library after files that reference it
# Works!
$ gcc main.c -lvector
Tip: The linker processes files left-to-right, maintaining a list of undefined symbols. Archives only satisfy undefined symbols seen so far.
Go deeper:
Eli Bendersky — Library order in static linking — exactly why a library must come after the files that need it.
ar(1) man page — creating and indexing the
.aarchive (r,c,sflags).