C Libraries: Static (.a) vs Dynamic Shared (.so / .dll) Libraries Masterclass
Welcome to Phase 21 (Chapter 59): C Libraries โ Static (.a) vs Dynamic Shared (.so / .dll) Libraries Masterclass! Software libraries allow sharing compiled code across projects. In this guide, you will master creating static libraries (`.a`), shared dynamic libraries (`.so`), and loading plugins at runtime with `dlopen()`.
| Feature | Static Library (.a / .lib) | Shared Dynamic Library (.so / .dll) |
|---|---|---|
| Link Time | Copied into executable at build time | Linked at launch time by OS dynamic linker |
| Executable Size | Larger (Bundles library code) | Smaller (Shared across multiple running processes) |
| Updates | Requires re-compiling executable | Update `.so` file on disk without re-compiling app! |
| Memory | Duplicated in RAM per running process | Single RAM physical page shared across processes |
Q1: Why is -fPIC mandatory for shared libraries?
Position Independent Code (`-fPIC`) generates memory addresses using relative offsets so the shared library can be loaded at any arbitrary RAM location.
Q2: How does LD_LIBRARY_PATH work on Linux?
An environment variable listing extra directory paths where the OS dynamic loader searches for `.so` shared libraries at app launch.
Q3: How do you load a C library plugin dynamically at runtime?
Use POSIX `dlopen("plugin.so", RTLD_LAZY)` to load, `dlsym(handle, "func_name")` to retrieve function pointers, and `dlclose()` to unload.
Q4: What is DLL Hell or Dependency Hell?
Incompatibility crashes when an updated shared library breaks application code expecting an older version of function signatures.
Q5: What is rpath in GCC linking?
The `-Wl,-rpath,.` flag bakes the shared library search path directly into the executable binary header.