Link Error w/Static Data Member

Hi everyone,

I have an EventManager class which makes use of static data members. I have declared them in both class and file scope, as follows:

1
2
3
4
5
6
7
8
9
10
class EventManager
{
...
private:
   static vector<Event> eventContainer;
   int refcount;
};

vector<Event> EventManager::eventContainer;
int EventManager::refcount;


This code, when not being used anywhere, compiles and links nice and fine. However, when I actually instantiate EventManager and attempt to access its data members through a friend class...
1
2
3
4
5
6
7
8
class TestModule
{
...
void test()
{
   Event Manager em;
   cout << em.refcount << endl;
}

I get a link error saying that there's multiple definitions of the data members. Does anyone know what's going on? I'm using MinGW 3.4.6.
Last edited on
You are instantiating the variable in the header file. This means that every .cpp file that includes the header file, directly or indirectly, gets an instantiation of the variable. If two .cpp files include the header, when you go to link them the variable is defined in both .o(bj) files.

Do not instantiate the variable in the header. Move it to a .cpp file.

Also, line 10 is wrong b/c refcount is not declared static.

Ahh, many thanks. Wouldn't have figured that out on my own.

And yeah, line 10 is a typo. My bad! :)
Topic archived. No new replies allowed.