Static vs Shared Libraries in C++
Libraries package reusable code: static libraries (.a/.lib) are copied into your executable at link time — bigger binaries, zero runtime dependencies, no version surprises. Shared libraries (.so/.dll/.dylib) load at run time — smaller binaries and shared updates, but the right version must exist on every machine that runs the program.
Build static with ar or -static, shared with -shared -fPIC; link with -L (where to look) and -l (what to link). Header + library + link flag is the universal trio for consuming any third-party C++ code.
Static: baked in
The linker copies .a code into your binary — self-contained executables that run anywhere, at the cost of size and re-linking on updates.
Shared: loaded live
.so/.dll files load when the program starts — one copy serves many programs and updates without recompiling them, but must be present (and compatible) at run time.
Build both from objects
Compile with -fPIC, then ar rcs libx.a *.o for static or g++ -shared -o libx.so *.o for shared — same objects, different packaging.
Consume with -L and -l
g++ app.cpp -L./lib -lfoo finds libfoo and links it; headers still come via #include as always.
// math.cpp → libmath.a, then:// g++ app.cpp -L. -lmath -o app#include <iostream>int triple(int x);int main() { std::cout << triple(7) << std::endl; return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C++ yourself — building beats watching.