0

i am trying to implement singleton on my io class i decleared two static members in the header file however the cpp does not know them.

class InputOutput{
//.h
private:
    System* s;
    static InputOutput* io;
    static pthread_mutex_t lock;
}

//.cpp
InputOutput* InputOutput::getInstance(){
static bool initiallized = false;
if (pthread_mutex_init(&lock, NULL) != 0){
    cout << "error in initiallize lock" << endl;
}

if(!initiallized){
    pthread_mutex_lock(&lock);
    if(!initiallized){
        io = new InputOutput();
        initiallized = true;
    }
    pthread_mutex_unlock(&lock);
}
return io;

}

the problem is: undefined reference to InputOutput::lock' undefined reference toInputOutput::io'

  • Static members of the class have to be defined in the .cpp file. They are only declared in the header. – Bo Persson Dec 31 '15 at 10:58
  • Are you using c++11? You can improve your signleton with c++11. Check this link http://elvisoric.blogspot.ba/2015/09/singleton-design-pattern.html – Elvis Oric Dec 31 '15 at 11:21

1 Answers1

0

Probably, You should initialize static members in your .cpp file like below,

InputOutput* InputOutput::io = NULL;
pthread_mutex_t InputOutput::lock;

Reason

Since static members are shared between ALL instances of a class, they have to be defined in one and only one place. If you define them like above in .h file, they will be defined in each .cpp file which includes that header file resulting in linking errors.

Pravar Jawalekar
  • 605
  • 1
  • 6
  • 18