class X
{
public:
staticint myStaticVar;
};
staticint 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.
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.
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.