Silverlan
Silverlan

Reputation: 2911

Global object constructor isn't getting called

Somehow my global objects are created without having their respective constructors called:

static int num = 0;
class TestClass
{
public:
    int a;
    float b;
    TestClass(float f)
    {
        a = 55;
        b = f;
        ++num;
    }
};
TestClass test(32);

int main(int argc,char *argv[])
{
    std::cout<<"Int: "<<test.a<<std::endl;
    std::cout<<"Float: "<<test.b<<std::endl;
    std::cout<<"Constructor has been called "<<num<<" times"<<std::endl;
    while(true);
    return 0;
}

The output is:

Int: 0
Float: 0
Constructor has been called 0 times

I've used constructors like this in different projects before and never ran into any problems like this. I've tried a parameterless constructor and making the test-variable static, neither had any different effect. Can anyone enlighten me about what's going on here?

I'm using visual studio 2010, in case that makes any difference.

Upvotes: 4

Views: 3294

Answers (2)

user4657571
user4657571

Reputation: 46

If you compile your project, which you link into your Executable, to an Executable-File, Visual Studio will link everything fine, but your Global-Constructor will not get invoked.

Upvotes: 0

Hauke P.
Hauke P.

Reputation: 2823

I'm not completely sure but this might answer your question: http://www.nsnam.org/docs/linker-problems.doc

Edited to add more information:

The document points out problems that can occur when using global constructors in different compilation units. For example if you define an object globally in some dynamically linked library, its object constructor might not be called when accessing a method from this library.

To use the example from the original question: The class TestClass and the global object test might be in TestLibrary.dll while the main() function is in some executable file. Depending on how the TestLibrary.dll is loaded and the test object is accessed from the executable, its constructor might never get called because the library is never "informed" that it was just loaded (or to put it differently: the global initialization function was never called).

Upvotes: 3

Related Questions