Learn C++
#include "tooling/libraries.hpp"

Static vs Shared Libraries in C++

//concept

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.

//how it works
1

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.

2

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.

3

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.

4

Consume with -L and -l

g++ app.cpp -L./lib -lfoo finds libfoo and links it; headers still come via #include as always.

//example
// 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;
}
Output
21
1triple is only declared here — its definition lives in the prebuilt libmath archive.
2-L. -lmath tells the linker where the library is and which one to pull in.
3The linked program calls into the library and prints 21 — reuse without recompiling the math code.
//use cases
Shipping self-contained tools with static linking
Sharing one library binary across plugins and programs with shared linking
Diagnosing cannot find -lfoo (wrong -L path) vs undefined reference (wrong link order/content)
Consuming third-party SDKs via their headers plus .a/.so pair

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.