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;
}