38

Duplicate:
C++: undefined reference to static class member

If I have a class/struct like this

// header file
class Foo
{
   public:
   static int bar;
   int baz;
   int adder();
};

// implementation
int Foo::adder()
{
   return baz + bar;
}

This doesn't work. I get an "undefined reference to `Foo::bar'" error. How do I access static class variables in C++?

Community
  • 1
  • 1
Paul Wicks
  • 62,960
  • 55
  • 119
  • 146

4 Answers4

71

You must add the following line in the implementation file:

int Foo::bar = you_initial_value_here;

This is required so the compiler has a place for the static variable.

Drakosha
  • 11,925
  • 4
  • 39
  • 52
20

It's the correct syntax, however, Foo::bar must be defined separately, outside of the header. In one of your .cpp files, say this:

int Foo::bar = 0;  // or whatever value you want
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • Hello Chris, Is there anything wrong if we have so many public static class member variables in c++ (non multi-threaded source code). I have moved some of my global variables to a class as public static. – uss May 26 '15 at 15:02
19

You need add a line:

int Foo::bar;

That would define you a storage. Definition of static in class is similar to "extern" -- it provides symbol but does not create it. ie

foo.h

class Foo {
    static int bar;
    int adder();
};

foo.cpp

int Foo::bar=0;
int Foo::adder() { ... }
Artyom
  • 31,019
  • 21
  • 127
  • 215
3

for use of static variable in class, in first you must give a value generaly (no localy) to your static variable (initialize) then you can accessing a static member in class :

class Foo
{
   public:
   static int bar;
   int baz;
   int adder();
};

int Foo::bar = 0;
// implementation
int Foo::adder()
{
   return baz + bar;
}