C ++ Singleton no se puede vincular en Mac OS

I am trying to create a very classic singleton on C++, Mac OS using Xcode I create the Class MySingleton as follow:

class MySingleton{
private:
    int val;
    static MySingleton *instance;
    MySingleton(){
        val = 0;
    }
public:
    int getVal(){
        return val;
    }
    void setVal(int iVal){
        val = iVal;
    }
    static MySingleton* getInstance(){
        if(instance == NULL)
            instance = new MySingleton();
        return instance;
    }

};

Linker is complaining about static MySingleton* getInstance() Follow the Linker message:

Undefined symbols for architecture x86_64: "MySingleton::instance", referenced from: MySingleton::getInstance() in main.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Could somebody help on this? Perhaps I need to set something on Xcode, which by the way is version 4.2.1, and I am not able in doing this. Thanks.

preguntado el 24 de agosto de 12 a las 04:08

As far as I can see, you've declared static MySingleton *instance but haven't defined it anywhere. -

So silly!!!! Thanks ta.speot.is!!! -

3 Respuestas

You need to define static variable in your cpp file, like this:

MySingleton *MySingleton::instance = 0;

Respondido 24 ago 12, 04:08

The static member MySingleton needs to be defined in the cpp file. In the header you have have only declared it. See this for more information: ¿Por qué las variables estáticas deben declararse dos veces en C ++?

contestado el 23 de mayo de 17 a las 13:05

As far as I can see, you've declared static MySingleton *instance but haven't defined it anywhere.

Respondido 24 ago 12, 04:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.