Static or Shared? A Guide to Choosing the Right Library When you're ready to package your software into a library, you have a fundamental choice to make: static or shared? Both are compiled. Both contain machine code. The difference is in how that code reaches the final executable. 📦 Static (.a / .lib) The linker copies the library's object code directly into your binary. The result is self-contained and no runtime dependencies. Delete the .a file afterward and your app still runs. 🔗 Shared (.so / .dll / .dylib) Your binary stores a reference. The OS loads the shared library into memory at runtime. Multiple programs can share a single copy in memory, but if the .so goes missing, your app won't start. When to reach for static: → Single, self-contained deployables (CLI tools, containers, embedded) → Maximum link-time optimisation (LTO can inline across the boundary) → Reproducibility is critical, no wrong .so version loaded at runtime When to reach for shared: → Multiple executables share the same library (one copy in memory) → Hot-patching / in-place upgrades without rebuilding consumers → Licensed libs that mandate dynamic linking And header-only? Just #include and go. Zero build friction. Perfect for template-heavy and constexpr code. The trade-off: every translation unit recompiles it, which can slow builds on large projects. What's your default choice when packaging a library? I'd like to hear your reasoning. #cpp #cmake #softwareengineering #libraries #programming
Worth noting: .a / .so are the Unix/Linux extensions. The same concept maps to .lib / .dll on Windows and .a / .dylib on macOS. CMake handles the naming for you so your CMakeLists.txt stays the same for all three platforms.
💡 Pro tip: You don't have to hardcode STATIC or SHARED in your add_library(), just omit it. The consumer then picks the strategy at configure time: cmake -DBUILD_SHARED_LIBS=ON .. → .so / .dll / .dylib cmake -DBUILD_SHARED_LIBS=OFF .. → .a / .lib (default) One CMakeLists.txt, both library types and the choice stays with whoever is building.