0

Here is a code sample:

// main.cpp
#include "test.hpp"
int main() {
    return 0;
}

// test.hpp
#include <iostream>
class Test {
public:
    static unsigned int count;
    Test() {
        std::cout << ++count << ", ";
    }
};
static Test test;

// test.cpp
#include "test.hpp"
unsigned int Test::count = 0;

The output result is:

1, 2, 

Why static variable in head file cause its constructor call twice?

p.s.

The constructor only call once if I put them within a file:

#include <iostream>
class Test {
public:
    static unsigned int count;
    Test() {
        std::cout << ++count << ", ";
    }
};
static Test test;
unsigned int Test::count = 0;
int main() {
    return 0;
}
Changkun
  • 1,502
  • 1
  • 14
  • 29
  • Because you are creating two instances? I don't get the question. Do you know what the `static` keyword does here or did you just guess? If the latter is the case: Looking up what stuff does works better than guessing. – Baum mit Augen Sep 13 '16 at 10:29
  • Duplicates: [Static variable in a Header File](http://stackoverflow.com/q/5040525/514235) ... and ... [initializing a static variable in header](http://stackoverflow.com/q/3837490/514235) ... and ... [Okay to declare static global variable in .h file?](http://stackoverflow.com/q/11967502/514235) ... – iammilind Sep 13 '16 at 10:29

0 Answers0