Reputation: 3331
Error: undefined reference to class_name::a
Upvotes: 0
Views: 1338
Reputation: 121961
From the error posted, the linker is stating that the variable has not been defined, not that it has not been explicitly initialised:
class A
{
// declaration.
static int x;
};
// definition (in this case without explicit initialisation).
int A::x;
The linker should not emit an error and the compiler should not emit a warning, as long as no attempt is made to use the static
variable before it has been assigned an initial value.
Upvotes: 5
Reputation: 92211
A static member is not really stored in any of the objects created, because it is shared between all objects of that class.
It should only be created once, even if you create many objects of that class. Or even if you create no objects of the class. Therefore you have to do it separately.
Compilers warn about all kinds of uninitalized variables, not only the static ones. Having a variable without a value is generally not very useful, so these warnings are good. Adding an = 0
is not too hard, is it?
Upvotes: 0