开发者

Initialization of const variables

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.开发者_JAVA百科)

Thanks a lot!


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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜