Thursday, March 26, 2009

Linking static libraries into a shared library

The ability to link static libraries into a shared library -- e.g.

gcc -shared -o lib1.a lib2.a lib3.a

-- disappeared in one of the 3.x series. This broke my tendency to build applications as static libraries, linked into a shared library, linked to by an executable consisting of little more than a main().

Turns out all that was missing was a GNU ld flag to prevent ld from optimizing the unused object code out of the shared library.

The solution is to wrap the .a files in --whole-archive flags, e.g.

gcc -shared -o -Wl,--whole-archive lib1.a lib2.a lib3.a -Wl,--no-whole-archive


  1. Thanks so much for this invaluable tip!

  2. Hi,
    I have really small toy example where I am building shared library from object files directly, but I want to build the shared library from the static library. It does not work even with your hint.

    The Makefile example is at (line 44):

    I appreciate any hint.Thanks

  3. Hi,
    great tip. Finally I made it working according your tip.
    Sorry for the previous post.

  4. This is an exquisite piece of advice. I was blindly trying to achieve a self-contained, portable .so file (with proprietary code, but whatever), by using some -l switches (as if linking statically to a library), but it was of course hopeless.

    I'm not sure if you always need to close with -Wl,--no-whole-archive, if the libraries to include come at the end of your command line.

    I can't say that I got my thing working all thanks to this (there are a few more hurdles to jump over), but this certainly brought me lightyears ahead.