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

2

30

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.

Emelinaemeline answered 22/1, 2011 at 12:58 Comment(0)
B
31

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

Boon answered 22/1, 2011 at 13:5 Comment(4)
-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 ?Emelinaemeline
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.Perianth
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 aboutMariejeanne
@nos: This is a fine answer; but I'm wondering if there's something less extreme; see this question of mine.Dittany
B
2

Use:

g++ -u <SYMBOL_NAME> ...

Note that -u is lowercase

Bolection answered 27/9, 2018 at 23:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.