views:

162

answers:

2

As I understand function-level linking builds (explicitly or not) a graph of all possible calls and only includes the reachable functions' code into the produced binary. But how does it deal with variables declared at file level?

Say I have

MyClass GlobalVariable;
static MyClass StaticGlobalVariable;

in some file that contains only these two variables and a set of functions not actually called from any of the remaining code.

Will the code for these variables allocation/initialization be included into the output?

+1  A: 

From experience (rather than quoting the standard):

If the initilaization has visible side effects like calls into external libraries or file I/O, the initialization will always happen.

boost::singleton_default provides an interesting solution that enforces the initialization to be done only when the object is referenced elsewhere, i.e. when all other references to the object are removed by the linker, the initialization is removed, too.

peterchen
A: 

Edit: Yes. g++ optimize flags try to figure out function calls and prune away .o files resulting in linker errors. I'm not sure if this happens only with certain optimize flags, but it does happen.

A bad habit in our company is the presence of a lot of 'extern g_GlobalFunction()' definitions in different files. As their calls depended on conditional code, the .o files were often thrown away, resulting in link errors.

We fixed that with g_InitModule() and g_InitFileName() calls that are called hierarchically starting from main(). Mostly, these are empty functions just meant to dissuade g++ from discarding the .o file.

Fox