I have this library which involves some static initialization code which needs to run before main()
. It all works well if you just compile all of the translation units together, but it doesn't work if I provide a static library (.a
file) and have users link their application against it - the linker simply ignores the symbols which do my static initialization.
Alternatively, I can make the linker pick up everything in the static library, if I specify the -Wl,--whole-archive
option to GCC, i.e. specify the --whole-archive
option to GNU link.
But is there some middle ground? Can I mark some symbols and make the linker always pick them up for the executable, while the rest of the symbols are added only when needed?
Motivation: I use some static blocks to register classes in a factory; I want to make my code available as a (non-dynamic) library, without the user code having to perform any "magic incantation" for the factory to be populated.
Some related questions:
--whole-archive
? – Bridging--undefined
is the only other solution. More details in https://mcmap.net/q/267351/-is-there-a-way-to-force-c-compiler-to-not-optimize-out-specific-static-objects-in-a-static-library – Bridging