When you have a static global variable in a C++ header file, each translation unit that includes the header file ends up with its own copy of the variable.
However, if I declare a class in that same header file, and create a member function of that class, implemented inline within the class declaration, that uses the static global variable, for example:
#include <iostream>
static int n = 10;
class Foo {
public:
void print() { std::cout << n << std::endl; }
};
then I see slightly odd behavior under gcc 4.4:
-
If I compile without optimization, all uses of the member function use the copy of the variable from one of the translation units (the first one mentioned on the g++ command line).
-
If I compile with
-O2, each use of the member function uses the copy of the variable from the translation unit in which the case is made.
Obviously this is really bad design, so this question is just out of curiosity. But my question, nonetheless, is what does the C++ standard say about this case? Is g++ behaving correctly by giving different behavior with and without optimization enabled?
The standard says (3.2/5):
This is where your code loses. The uses of
nin the different definitions ofFoodo not refer to the same object. Game over, undefined behavior, so yes gcc is entitled to do different things at different optimization levels.3.2/5 continues:
So in your example code you could make
ninto astatic const intand all would be lovely. It’s not a coincidence that this clause describes conditions under which it makes no difference whether the different TUs “refer to” the same object or different objects – all they use is a compile-time constant value, and they all use the same one.