1

I have a class like this:

class example {
public:
    static void setStaticVar() { example::var = 1; };
private:
    static int var;
};

But it gives me linker errors and I have no idea why. I want to store some data in the variable that is the same for every instance. That's why I want to use a static variable instead of an instance variable (with an instance variable I would store the same data in every single instance of the class which is a waste of memory).

How do I do this?

notadam
  • 2,754
  • 2
  • 19
  • 35

3 Answers3

2

In the source file

int example::var = 0;

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
2

You need to initialize the variable once. In one .cpp, outside of any functions, you have to initialize the variable:

int example::var = 0;
clcto
  • 9,530
  • 20
  • 42
2

You must initialize it out of the class definition.

Try this.

class example { ... };

// initialize it to avoid linker errors
int example::var = 1;
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
  • 1
    If that is in a header file that is included multiple places, you will get multiple definition errors. – clcto Jul 30 '14 at 16:50
  • 1
    That is correct. Typically static variables should be initialized in the `.cpp` files. That however isn't the case if you use header guards, which should be always. – Austin Brunkhorst Jul 30 '14 at 16:50