2

I've declared a public static member to keep the total count of the instances of my class. The code is as follows:

class Hello {
public:
    static int myCount;
    void test(){
        //do nothing
    };
    Hello(){
        Hello::myCount += 1;
    };
    ~Hello() {
        Hello::myCount -= 1;
    }
};

int main(int argc, const char * argv[]) {
    // insert code here...
    Hello *p1 = new Hello();p1->test();
    Hello *p2 = new Hello();p2->test();
    cout << Hello::myCount;

    return 0;
}

However, I when compile, it says:

Undefined symbols for architecture x86_64:
  "Hello::myCount", referenced from:
      _main in main.o
      Hello::Hello() 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)

I don't know where I'm wrong. It's been years from the last time I worked with c++, so could you please suggest a solution? Thank you.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
lenhhoxung
  • 2,530
  • 2
  • 30
  • 61

1 Answers1

4

Static members have to be defined outside of the class, e.g.:

class Hello {
public:
    static int myCount;
    void test(){
        //do nothing
    };
    Hello(){
        Hello::myCount += 1;
    };
    ~Hello() {
        Hello::myCount -= 1;
    }
};

int Hello::myCount = 0; // definition outside of the class

(...)

Here is an example to show, that it helps to solve your problem: http://ideone.com/LVXVCc

It's all because a rule called One Definition Rule.
You can read more about this one in a context of static class members here.

In short: static int myCount declaration is not a definition of a member. Classes are usually placed in their .h/.hpp header files and are included to many other files. If those'd contain static member and lines like the one above would be a definition, it will lead to the multiple-definitions error.

To prevent that, this declaration is not treated as a definition and you must define it yourself later.

mtszkw
  • 2,717
  • 2
  • 17
  • 31