0

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

The following C++ code compiles well (using g++ -c) but it doesn't link giving the error: undefined reference toAbc::X'`

#include <iostream>

using namespace std;

class Abc {

public:
    const static int X = 99;
};

int main()
{
    Abc a1;
    cout << &(Abc::X) << endl;
}

I want to know why this is not allowed?

Community
  • 1
  • 1
Xolve
  • 22,298
  • 21
  • 77
  • 125

3 Answers3

4

You need to have that static member actually defined, not just declared...

Add this line before your main():

const int Abc::X = 99;

As of C++17 you can also do an inline static, in which case the above additional line of code in a .cpp file is not needed:

class Abc {

public:
    inline const static int X = 99; // <-- "inline"
};
YePhIcK
  • 5,816
  • 2
  • 27
  • 52
1

If you don't like to think about translation units, static initialization order and stuff like that, just change your static constants into methods.

#include <iostream>
using namespace std;

class Abc {

public:
    inline static const int& X(){ 
      static int x=99;
      return x; 
    }
};

int main()
{
//    Abc a1;
    cout << &(Abc::X()) << endl;
}
Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
  • In fact not looking for a quick solution. Would be glad to read detailed explanation (or links to explanations) about "translation units, static initialization order and stuff like that". – Xolve Jul 15 '12 at 07:47
  • Right. There's a lot about those words on SO and google. Or even better, any entry-level book from this list: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list, perhaps I'll add more later. – Johan Lundberg Jul 15 '12 at 08:12
1

If the static member is used in a way which requires an lvalue (i.e. in a way that requires it to have an address) then it must have a definition. See the explanation at the GCC wiki, which includes references to the standard and how to fix it.

Jonathan Wakely
  • 166,810
  • 27
  • 341
  • 521