How to force gcc to link unreferenced, static C++ objects from a library

14,778

Solution 1

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

Solution 2

Use:

g++ -u <SYMBOL_NAME> ...

Note that -u is lowercase

Share:
14,778
Gene Vincent
Author by

Gene Vincent

Updated on June 07, 2022

Comments

  • Gene Vincent
    Gene Vincent almost 2 years

    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.

  • Gene Vincent
    Gene Vincent over 13 years
    -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 ?
  • Yttrill
    Yttrill over 13 years
    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.
  • Michael Mrozek
    Michael Mrozek over 10 years
    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
  • einpoklum
    einpoklum about 7 years
    @nos: This is a fine answer; but I'm wondering if there's something less extreme; see this question of mine.