3

I want to have a simple class i can call to get a unique number whilst the program is running - i can do the below with a dynamic allocation, and then just delete when not needed, but i still wanted to get a static version too. Strangely, the code below (which is seemingly straightforward) throws some strange comiple errors (appended below).

Any ideas whats going on ? is this an incorrect use of static ?

class Id_gen {
    private:
 //adding static here stops the code from compiling:
 static int curr_id;

    public:

 Id_gen() {curr_id = 1; cout<<"debug:constructed"; }
 int get_id() {curr_id++; return curr_id; };
};

int main () {


    Id_gen bGen;
    cout << bGen.get_id() <<endl;

return 0;    
}

running g++ (linux 64):

c++2.cpp:(.text._ZN6Id_genC1Ev[Id_gen::Id_gen()]+0xe): undefined reference to `Id_gen::curr_id'
/tmp/cc766N6p.o: In function `Id_gen::get_id()':
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0xa): undefined reference to `Id_gen::curr_id'
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0x13): undefined reference to `Id_gen::curr_id'
c++2.cpp:(.text._ZN6Id_gen6get_idEv[Id_gen::get_id()]+0x19): undefined reference to `Id_gen::curr_id'
2
  • Those are link errors, not compile errors.
    – TheJuice
    Commented May 11, 2010 at 9:04
  • 1
    Those are linker errors, not compile time errors. The distinction matters - particularly once you start working in teams and are creating libraries for your colleagues. Commented May 11, 2010 at 9:07

5 Answers 5

3

Add the initialization/definition of the static member as:

int Id_gen::curr_id = 0;

after the class definition.

EDIT: As mentioned in the comment by @sbi : Initialization is optional, the linker requires the definition only.

1
  • Initialization isn't important for the linker. It's the definition the linker needs.
    – sbi
    Commented May 11, 2010 at 8:48
2

You need to define the static variable outside the class as:

int Id_gen::curr_id;
0

You have to define the static member in a translation unit (cpp file):

int Id_Gen::curr_id = 0; // Initial value
0

You must define the static instance variable in your class implementation, i.e.:

int Id_Gen::curr_id = 0;
0

As mentioned by others you need to define the variable outside of the class:

int Id_Gen::curr_id;

If there is nothing else in this class you could omit the constructor and initialise this variable when you define it and make the get_id() function static too. This would allow you to call Id_Gen::get_id() without creating an instance of the class. In its current state if you mistakenly created two Id_Gen's you would reset your id.

Not the answer you're looking for? Browse other questions tagged or ask your own question.