7

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?

2
  • Please fix your typing mistakes and what is the difference between your case 1 and case 2? Commented Jun 3, 2016 at 12:16
  • The first case in the cpp with other big code and second case in the new file Commented Jun 3, 2016 at 12:28

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Classes do not exist in object files. What this answer says about the "class TestStruct actually applies to the variable t, right?
That, and the class's constructor.
Sure, but the presence of the constructor itself is not really the subject of the question, I would say. It's its call when creating t.
Thank you it works, when I use TestStruct in main.cpp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.