You have specified your identifier as static:
static unsigned int CIDCounter = 0;
which means that each compilation unit will receive its own copy of the variable. Instead, you should declare it as extern in the header file:
extern unsigned int CIDCounter;
and initialize it in the implementation file
unsigned int CIDCounter = 0;
It should be noted that without appropriate locks this will not be thread safe.
To clarify:
The static in this context means that a variable or function is limited to the current compilation unit (usually a cpp file). I assume that you have, say, main.cpp and idcounter.cpp , so now we have two variables (one for each compilation unit) main_CIDCounter and idcounter_CIDCounter (variable names are for explanation only!).
When you execute your test code in main.cpp, the template function sees main_CIDCounter , because the current compilation unit and you get the expected 1,2,3. However, when calling ComponentCount() , the code from idcounter.cpp , and this code sees idcounter_CIDCounter - which has not been changed at all. If you had different compilation units, you would see a similar behavior where each cpp file would seem to support its own ID counter.
The fix I described just has only one copy of CIDCounter in idcounter.cpp and declares it as external in all other compilation units.
source share