0

The code is as below:

#include <iostream>

using namespace std;

class A {
    static int id_;

public:
    static void setId(int id) {
        id_ = id;
    }
    static int getId() {
        return id_;
    }
};

int main()
{
    A::setId(10);
    cout << A::getId() << endl;
    return 0;
}

When I compile it in Xcode, Mac OS, there's an error message:

Undefined symbols for architecture x86_64:
  "A::id_", referenced from:
      A::setId(int) in main.o
      A::getId() in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

If I add the line:

int A::id_ = 10;

before the main(). Then, everything is fine. What's the reason with it?

Shafik Yaghmour
  • 143,425
  • 33
  • 399
  • 682
injoy
  • 3,197
  • 7
  • 29
  • 54

2 Answers2

3

Variables need to be declared and defined and the draft C++ standard section 9.4.2 Static data members says:

The declaration of a static data member in its class definition is not a definition [...]

so it must be defined, which is why you need to add:

int A::id_ = 10;

and to see this more clearly, we see that:

int A::id_ ;

is sufficient, we don't have to initialize A::id_ just define it.

You may also want to read this previous thread: What is the difference between a definition and a declaration?.

As Steve points out when you move to using header files you will need to define your variable in the cpp file since you do not want more than one definition.

Community
  • 1
  • 1
Shafik Yaghmour
  • 143,425
  • 33
  • 399
  • 682
  • 1
    And if you move your class to a header file, as will happen if your project gets bigger, the definition has to be in a .cpp. – Steve Howard Nov 01 '13 at 19:36
2

Once a class object is made certain compilers do not allow creation of static variables without initialization.

Sohaib
  • 4,058
  • 7
  • 35
  • 66