Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't increment a static variable

Tags:

c++

Could you help me understand why I can't increment the static variable? I face this: *error LNK2001: unresolved external symbol "private: static unsigned int Counter::m_curCounters" (?m_curCounters@Counter@@0IA)*

counter.cpp

#include "counter.h"

static unsigned int m_curCounters = 0;

Counter::Counter(const char* p){
    ...
    m_curCounters++;
}


Counter::Counter(){
    ...
    m_curCounters++;
}
like image 913
Trts Avatar asked Dec 26 '22 05:12

Trts


2 Answers

I think whats happening here that you have m_curCounters declared in counter.h and that you create a new local static in the cpp. But class statics need to be visible to the linker by defining them in the cpp as unsigned int Counter::m_curCounters = 0;

Now when you try to use the local static the compiler gives precedence to the class static which the linker cant find later on

like image 167
Serve Laurijssen Avatar answered Jan 08 '23 14:01

Serve Laurijssen


I suppose you have m_curCounters declared in Counter.
Then you need to define it as

unsigned int Counter::m_curCounters = 0;
like image 32
alexrider Avatar answered Jan 08 '23 14:01

alexrider