Search code examples
c++singletonunresolved-external

Avoid unresolved externals when implementing singleton pattern


Consider following MRE:

class Segment
{
public:
    void update();
};

class Singleton
{
    Singleton();
public:
    static Singleton& get_instance();
    void complete();
};

void Segment::update()
{
    Singleton::get_instance().complete();
}

Singleton& Singleton::get_instance()
{
    static Singleton instance;
    return instance;
}
void Singleton::complete()
{}

int main()
{
    return 0;
}

When I compile the code under standard Debug configuration in VS2019, I get a linker error about unresolved external for function get_instance().

Full error description

LNK1120 1 unresolved externals
LNK2019 unresolved external symbol
"private: __cdecl Singleton::Singleton(void)"
(??0Singleton@@AEAA@XZ) referenced in function
"public: static class Singleton & __cdecl Singleton::get_instance(void)"
(?get_instance@Singleton@@SAAEAV1@XZ)

I declared the classes first, then I implemented all the methods so what's wrong?


Solution

  • You are missing the definition of the constructor used in your static member-function (Singleton::Singleton()); it is not complaining about the static member-function itself (which is properly defined).

    Either remove the declaration, as said constructor is not necessary in your example, declare it as Singleton() = default; (c++11), or write the appropriate code to actually define it.

    It is all stated in the diagnostic, you just need to read it more carefully.