Defining a static member variable

Lets say I have a class in a header file as such:

1
2
3
4
5
6
7
class X
{
public:
    static int myStaticVar;
};

static int X::myStaticVar = 5;


Now every time I include this header file elsewhere, it gets its own copy (aka redefined). I know that if I just define myStaticVar elsewhere (in a file that never gets included), things work out. But that doesn't make sense, right? Defining the variable in the middle of nowhere!

So how should I do this? I believe it has something to do with extern, but I don't really know how to use it.
Last edited on
You are starting with an error in your assumption:

static int X::myStaticVar = 5;//Error - cannot re-use the static keyword here.
Last edited on
Whoops, ignore that part..

1
2
3
4
5
6
7
class X
{
public:
    static int myStaticVar;
};

int X::myStaticVar;
I think it makes sense. That's how C++ works. You have to put the int X::myStaticVar = 5; line in a file that is not included. Normally each class is split into a header and a source file. myStaticVar is a member of X so it make sense to placed it in X's source file.
Last edited on
Oh, I thought it involved using extern or something like that.
When you include your header file with X's definition in other .cpp files, those files do not receive their own copy of the X::myStaticVar variable. What the header file tells the compiler is "there is a variable named myStaticVar, and its storage is in some other location - I don't need to know where it is, the linker will tell me later". So there will only ever be one X::myStaticVar. When you actually define it in a .cpp file, that is the memory all the other .cpp files will eventually reference.

Note that this behavior is different from a global variable with the static keyword - in that case, you are explicitly telling the compiler that the variable is being defined locally, and that it should not look for linkage externally in other object files or libraries. "Extern" comes into play when you want to tell the compiler that a particular variable is defined outside of the current .cpp file, and that it needs to be handled during program linking.
Topic archived. No new replies allowed.