1

It has been a while since I've programmed in C++. I was trying to implement a singleton class, but I get an unresolved external symbol. Can you guys point out out to resolve this problem? Thanks in advance!

class Singleton
{
    Singleton(){}
    Singleton(const Singleton & o){}
    static Singleton * theInstance;

public:
    static Singleton getInstance()
    {
        if(!theInstance)
            Singleton::theInstance = new Singleton();

        return * theInstance;
    }
};

Errors:

Error 3 error LNK1120: 1 unresolved externals

Error 2 error LNK2001: unresolved external symbol "private: static class Singleton * Singleton::theInstance" (?theInstance@Singleton@@0PAV1@A)

Community
  • 1
  • 1
user625665
  • 45
  • 1
  • 6

3 Answers3

9

You have declared Singleton::theInstance, but you have not defined it. Add its definition in some .cpp file:

Singleton* Singleton::theInstance;

(Also, Singleton::getInstance should return a Singleton& rather than a Singleton.)

ildjarn
  • 62,044
  • 9
  • 127
  • 211
  • 1
    You want to return a reference here rather than a pointer b/c a singleton differs from a typical factory. A factory gives up ownership of the object, while a singleton does not. This explains it well http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt – jdt141 Jun 27 '11 at 01:08
4

You need to provide a definition of theInstance outside the class declaration, in a C++ implementation file:

Singleton *Singleton::theInstance;
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
2

Alternatively to all the other answers, you could just do away with the private member and use a static-scope function variable:

static Singleton getInstance()
{
   static Singleton * theInstance = new Singleton(); // only initialized once!
   return *theInstance;
 }
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084