Loading lessons...
Static and Dynamic Libraries
Static and Dynamic Libraries
Very little C++ ships as a single huge file. Reusable compiled code is packed into libraries, either static or dynamic.
What a library is
A library is precompiled, reusable code. Instead of rewriting math, strings, or containers each time, you link against a library that already has it.
Static libraries
A static library is archived object code:
- Windows:
.lib - Linux/macOS:
.a
At build time, the linker copies the needed code into your executable. The result is self-contained, but every binary duplicates the shared code.
ar rcs libmymath.a mymath.o
g++ main.cpp libmymath.a -o app
Dynamic libraries
A dynamic library is loaded at runtime:
- Windows:
.dll - Linux:
.so - macOS:
.dylib
Many program share one copy in memory, so disk and RAM use go down. The catch: that shared copy must exist when the program runs.
g++ -shared -fPIC mymath.cpp -o libmymath.so
g++ main.cpp -lmymath -o app
Linking
Linking joins your object files with the libraries you need. Static linking bakes the code in; dynamic linking leaves a reference the loader resolves at runtime. The standard library is usually freestanding, but your machine's runtime provides its dynamic copy.
Why use libraries
- Reuse: write once, use in many programs.
- Update: fixing one DLL fixes every app using it.
- Smaller executables with dynamic linking.
- Faster builds, because library code rarely recompiles.
TL;DR
- Libraries bundle precompiled reusable code.
- Static (
.lib/.a): copied into the executable at link time. - Dynamic (
.dll/.so/.dylib): loaded at runtime, shared. - Static is self-contained; dynamic saves space but needs the library present.
- Linking is the step that joins your code and the library.