Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top