0

Possible Duplicate:
Defining static members in C++
Static method with a field

I found the below code on singleton implementation on the web, and decide to give it a try:

#include <iostream>

class Singleton
{
    Singleton(){}
    static Singleton *s_instance;

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

        return s_instance;
    }
};

int main()
{
    Singleton::getInstance();
    return(0);
}

It looks quite straight forward. But when I build it in Visual Studio, it gives a linker error message:

main.obj : error LNK2001: unresolved external symbol "private: static class Singleton
* Singleton::s_instance" (?s_instance@Singleton@@0PAV1@A)
C:\Users\boll\Documents\Visual Studio 2010\Projects\hello_world\Debug\hello_world.exe :
fatal error LNK1120: 1 unresolved externals'

Why is 's_instance' unresolved in this case?

Community
  • 1
  • 1
user1559625
  • 2,583
  • 5
  • 37
  • 75
  • 2
    Have a look at this: http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix – chris Sep 25 '12 at 01:34
  • You need to define `s_instance` outside the class. – Mysticial Sep 25 '12 at 01:34
  • got it. Thanks chris and Mysticial. – user1559625 Sep 25 '12 at 01:37
  • possible duplicate of [Defining static members in C++](http://stackoverflow.com/questions/3536372/defining-static-members-in-c) also http://stackoverflow.com/questions/8612206/linker-error-when-using-static-members, http://stackoverflow.com/questions/3585069/weird-linker-error-with-static-stdmap , and more – Seth Carnegie Sep 25 '12 at 01:48
  • actually a little question here: static data member need to be defined once outside of class, that's c++ rule. but why? static member function 'getInstance()' has visibility if we use scope ::, but why 's_instance' cause the unresolved external symbol error? – user1559625 Sep 25 '12 at 01:56

1 Answers1

0

I think you should initialize s_instance=NULL before. You can see the following link: http://www.codeproject.com/Articles/1921/Singleton-Pattern-its-implementation-with-C

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278