views:

72

answers:

2

Hi all,

I have code like this:

bool doSomething()
{ 
  std::cout << "I'm here!"
  return true;
}
const bool x = doSomething();

If placed in a cpp-file in my Visual C++ console application, the code is executed as expected before entering the main() method.

However, if I place this code in a .cpp-file inside a static link library project (which is linked to my console application), the code is never executed. I do not define any methods in this file that are used from outside, there is no according .h-file. So is it possible that the linker doesn't link the file? How can I avoid this?

(Actually the code gets executed if I create a header file for the cpp file, place another method "void dummy() {}" inside the cpp- and h-file and call dummy() from main.)

Thanks a lot!

+1  A: 

When the code is in a static library, the linker will only link it in if it's actually used. This reduces the size of your binary file.

Steve Townsend
well, that's ok, but my method doSomething() actually does something (as the name says :-)). In my concrete case it registers a type at a factory-singleton which is used from other parts. So this "optimization" leads to changed behavior. Is that ok?
Philipp
It's not OK, but there is no way for the linker to know that you want this code to be executed in the library client. It would be better to use some alternative method to expose this needed call, where the client has to actually trigger the library init somehow, by external reference to this code that causes it to be pulled at the link step.
Steve Townsend
+4  A: 

This should set things straight.

$3.6.2/4- "It is implementation-defined whether the dynamic initialization of a non-local variable with static storage duration is done before the first statement of main. If the initialization is deferred to some point in time after the first statement of main, it shall occur before the first use of any function or variable defined in the same translation unit as the variable to be initialized.34"

Chubsdad