No global variable initialization

When I add this code to an existing cpp with one of my class implementations

#include <iostream> struct TestStruct{ TestStruct(int i) { std::cerr << i << std::endl; x = i; } int x; }; TestStruct t(8); 

It prints 8 before doing main .

But when I created a new empty test.cpp file and put the same code into it, nothing was printed. I checked that this cpp has been compiled and linked. All cpp files are compiled as a static lib, and then this lib with main.o is linked into an executable file. I use only g ++ 5.3 only -std=C++14 .

Why is the second case missing the initialization of the global variable?

+7
c ++ g ++ c ++ 14
source share
1 answer

You added the TestStruct class as a separate module in the static library and linked it to your executable.

The whole purpose of using a static library is that only modules that have any characters, classes, or other resources referenced by the executable that you link to are associated with the executable. Modules in a static library that do not have any characters that directly or indirectly refer to the main executable file are not tied to the main executable file. This is what a static library is.

Because your executable did not have explicit references to the TestStruct class, the module was not associated with your executable and did not become part of the final executable.

But when you add the TestStruct class to an existing module that your executable is already referencing and using (directly or indirectly), this class, along with all the other symbols and classes from another module, connects to your executable and become part of the final executable.

Since your executable file refers to some symbol or other resources in this other module, everything in this module, including the test class, is bound to the executable file.

+8
source share

All Articles