0

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?

user4581301
  • 31,330
  • 6
  • 30
  • 51
sanitizedUser
  • 1,456
  • 3
  • 14
  • 28
  • 1
    Where is the definition of ` Singleton::Singleton()` ? Looks like you left it out. – user4581301 Dec 31 '20 at 19:33
  • 2
    "_I get a linker error about unresolved external for function `get_instance()`_" No, you get error about `"private: __cdecl Singleton::Singleton(void)"` **referenced** in `get_instance()`. – Algirdas Preidžius Dec 31 '20 at 19:35

1 Answers1

1

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.

Filip Roséen - refp
  • 60,448
  • 19
  • 148
  • 192