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?
In C language both the global and static variables must be initialized with constant values. This is because the values of these variables must be known before the execution starts. An error will be generated if the constant values are not provided for global and static variables.
An uninitialized variable is a variable that has not been given a value by the program (generally through initialization or assignment). Using the value stored in an uninitialized variable will result in undefined behavior.
Yes, all members of a are guaranteed to be initialised to 0. If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.
Why Doesn't Java use Global Variables? The short answer to this question is: intentional design. Java was created as a purely object-oriented programming language, which is why everything you create is wrapped in a class.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With