Static data members = fail

Why does this show me this error

undefined reference to `SomeClass::data'


1
2
3
4
5
6
7
8
9
10
class SomeClass
{
	public:
		static int data;
} ;

int main()
{
	SomeClass::data = 12;
}


Also if I create a variable that is of SomeClass it throws the same error.
I'm not entirely sure why this happens, maybe someone can explain it, but it can be solved by forward declaring it outside that class definition like so:

int SomeClass::data;
making a static member var is similar to making an extern global var. It tells the compiler it exists somewhere but doesn't actually allocate memory for it.

I often compare it to function prototypes vs. function bodies. Writing a prototype lets you call the function in your code, but unless you actually give the function a body, you'll get linker errors if you try to use it.

Likewise, putting a static member var in your class will let you use that variable in your code, but unless you actually give it a body (instantiate it), you'll get linker errors if you try to use it.


The line slicedpan is what instantiates the variable.

Note that it must only be instantiated once. This means you cannot put that line in a header file, otherwise it will be instantiated in every cpp file that includes that header. You must instantiate it in one and only one cpp file.
This is what I now have for main
1
2
3
4
int main()
{
	int SomeClass::data = 12;
}


And it throws this error

error: invalid use of qualified-name 'SomeClass::data'
the instantiation has to be declared globally, not in any function:

1
2
3
4
5
6
7
8
9
10
11
12
//your cpp file

#include "someclass.h"

int SomeClas::data = 12;

//======================

int main()
{
  //...
}
It works! Thanks for the help.
Topic archived. No new replies allowed.