Yet another static
question.
I have read the following:
- What are static variables?
- file scope and static floats
- http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
And I still fail to understand the following behavior:
I have one h
file:
// StaticTest.h
#include <stdio.h>
static int counter = 0;
struct A {
A () {
counter++;
printf("In A's ctor(%d)
", counter);
}
~A () {
counter--;
printf("In A's dtor(%d)
", counter);
}
};
static A a;
And two cpp
files:
// StaticTest1.cpp
#include "StaticTest.h"
int main () {
return 0;
}
And:
// StaticTest2.cpp
#include "StaticTest.h"
The output of the program is:
In A's ctor(1)
In A's ctor(2)
In A's dtor(1)
In A's dtor(0)
Now, A
's constructor is called twice, since the h
file is included twice, and since A
's instance named a
is declared static
, it has internal linkage and the compiler is happy.
Since the counter
is also declared static, it also has internal linkage, and I would expect that it's value will not be shared in the two cpp
files --- but the program output implies the value is shared, since it counts up to 2.
any insights?
EDIT:
Any answers regarding what is considered a "good programming habit" in the context of declaring static variables in h
vs. cpp
files is also welcomed.