29

I'm using a C++ library that can be built as either a shared or a static library. This library uses a factory technique, where static objects register themselves when the program starts and the static objects get created.

This works fine as long as the shared library is used. When the static version is used, none of the static objects get included into the final program (because they aren't referenced directly) and thus their functionality isn't available.

Is there a way to force gcc to include all static objects from a library when linking?

The library is Open Source and I could modify it, if that helps.

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Gene Vincent
  • 4,721
  • 7
  • 43
  • 82

2 Answers2

28

You can use -Wl,--whole-archive -lyourlib , see the manpage for ld for more info.

Any static libraries mentioned after -Wl,--whole-archive on the command line gets fully included, you can turn this off again too if you need to , as in e.g. -Wl,--whole-archive -lyourlib -Wl,--no-whole-archive -lotherlib

nos
  • 207,058
  • 53
  • 381
  • 474
  • 5
    -Wl,--whole-archive causes a lot of symbols to be included that are already included by other libraries or some that can't be resolved. Is there a more fine grained way ony to include the statics ? – Gene Vincent Jan 22 '11 at 13:15
  • This doesn't make sense Gene: its the same as loading a shared library: you get the whole library, and nothing else. Admittedly ld has a screwed up notion of finding external references, so you need to get the order of things right. – Yttrill Jan 22 '11 at 13:40
  • 8
    Shutting off the behavior with `-Wl,--no-whole-archive` is actually not optional, even if you have no more libraries to include. GCC will add all the standard system libraries to the end of your command, so if you leave `--whole-archive` on they'll all be affected by it and it will cause the duplicate symbol problem @GeneVincent commented about – Michael Mrozek Oct 01 '13 at 22:54
  • @nos: This is a fine answer; but I'm wondering if there's something less extreme; see [this question](http://stackoverflow.com/questions/43471071/when-linkung-is-there-something-between-grab-what-you-need-and-grab-all-w) of mine. – einpoklum Apr 18 '17 at 11:39
2

Use:

g++ -u <SYMBOL_NAME> ...

Note that -u is lowercase

PA314159
  • 106
  • 1
  • 6