Sergey Kolesov
Sergey Kolesov

Reputation: 486

No Global variable initialization

When I add this code in existing cpp with one of my class implementation

#include <iostream>

struct TestStruct{
    TestStruct(int i)
    {
        std::cerr << i << std::endl;
        x = i;
    }
    int x;
};

TestStruct t(8);

It prints 8 before main executed.

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

Why in the second case global variable initialization are missed?

Upvotes: 7

Views: 190

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

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

The whole purpose of using a static library is that only the modules which have any symbols, classes, or other resources that are referenced by the executable you're linking with -- they get linked into the executable. Modules in a static library that do not have any symbols that are referenced, directly or indirectly, by the main executable do not get linked into the main executable. That's what a static library is all about.

Because your executable had no explicit references to the TestStruct class, the module did not get linked into your executable, and did not become a part of the final executable.

But when you added the TestStruct class in an existing module that your executable already references and uses (either directly or indirectly), then this class, together with all other symbols and classes from the other module, get linked into your executable and become a part of the final executable.

Because your executable references some symbol or other resources in that other module, everything in that module, including the test class, gets linked into the executable.

Upvotes: 8

Related Questions