Trick for building modular static libraries

 Sometimes one may wish to build static library (i.e. .a archive) in modular fashion, so that indepndent components could be dynamically loaded using dlopen(3). But this leads to linking problems, as linker tries to be smart enough, and removes not referenced symbols, thus later, when dynamic component is loaded, it's unable to find symbols in main executable it depends upon.
 There are two ways to solve this problem:

  1. Link each component with main executable as dynamic library
  2. Force linker to include whole main library into executable

First approach is simple, but it means that your library has always be linked dynamically, which is may be not what you want. Second approch is compiler (actually linker) specific, and works like this:

  • Linux:  gcc -Wl,--whole-archive libMY.a -Wl --no-whole-archive
  • Solaris:  gcc -z allextract libMY.a