So I wonder if there is a specific way to tell the linker to not drop specific function call, instead of changing link options for entire program.
Your objective is actually to tell the linker not to drop the definition of an unreferenced variable (dummy
) in whose
initialiser there is a function call that you wish to ensure is executed by your program.
__attribute__(used)
is an attribute of functions, but not of variables, and its effect is to force the compiler to compile the function definition,
even if the function is static and appears unreferenced in the translation unit. In your case:
bool dummy = (Register(), false);
it cannot appear to the compiler that Register
is unreferenced - it is called - so __attribute__(used)
will
be redundant even if the definition of Register()
is in the same translation unit and is static. But whether or
not the definition of Register()
is compiled in this translation unit or some other, this call to Register()
will not be linked or executed in the program if this definition of dummy
is not linked.
I assume you do not want to write a custom linker script, or to modify the source code so that dummy
is referenced.
In that case you need to instruct the linker to postulate an undefined reference to dummy
, by
passing --undefined=dummy
in its options. This will force it to search libraries for
a definition of dummy
, and to link archive members (and/or shared libraries) exactly as if there
actually was an undefined reference to dummy
in the first file that is linked. No redundant code will be linked,
as is probable with --whole-archive
.
You can pass --undefined=<symbol>
to the linker for as many values of <symbol>
as
you like. To pass it through gcc/g++
, use -Wl,--undefined=<symbol>
.