I\'m getting an Undefined reference error message, on this statement:
GlobalClass *GlobalClass::s_instance = 0;
Any ideas? Code is shown be
When you declare a static field s_instance
in your .h file, it only tells the compiler that this field exists somewhere. This allows your main
function to reference it. However, it doesn't define the field anywhere, i.e., no memory is reserved for it, and no initial value is assigned to it. This is analogous to the difference between a function prototype (usually in a .h file) and function definition (in a .cpp file).
In order to actually define the field, you need to add the following line to your .cpp file at global scope (not inside any function):
GlobalClass* GlobalClass::s_instance = 0;
It is important that you don't add the static
modifier to this definition (although you should still have the static
modifier on the declaration inside the class in the .h file). When a definition outside a class is marked static
, that definition can only be used inside the same .cpp file. The linker will act as if it doesn't exist if it's used in other .cpp files. This meaning of static
is different from static
inside a class and from static
inside a function. I'm not sure why the language designers used the same keyword for three different things, but that's how it is.