1

Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?

Why do I have a "undefined reference to Monitor::count" error for the following code? Thanks!

#include <iostream>

using namespace std;

class Monitor
{
    static int count;
public:
    void print() { cout << "incident function has been called " << count << " times" << endl; }
    void incident() { cout << "function incident called" << endl; count++; }
};

void callMonitor()
{
    static Monitor fooMonitor;
    fooMonitor.incident();
    fooMonitor.print();
}

int main()
{
    for (int i = 0; i < 5; i++)
        callMonitor();
    return 1;
}
Community
  • 1
  • 1
user673769
  • 37
  • 2
  • 4

2 Answers2

10

Because you declare it but do not define it. Put the following in one (and only one) of your .cpp files:

int Monitor::count = 0;
ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • isn't static variable default be initialized to be 0? – user673769 Apr 08 '11 at 21:53
  • 2
    @user673769 : Yes, §8.5/6 guarantees that all static objects will be at a minimum zero-initialized. So, you could shorten the definition to `int Monitor::count;` if you want, but a definition is necessary either way. – ildjarn Apr 08 '11 at 22:00
2

You have not defined the static variable count.

class Monitor
{
     // ...
};

int Monitor::count = 0 ;

// ...
Mahesh
  • 34,573
  • 20
  • 89
  • 115