Unresolved External Symbol in Singleton Class

爷,独闯天下 提交于 2019-12-24 16:15:52

问题


I've been coding for a long time now but I do not understand this error. I am writing a custom system for providing unique integer ID's to specific instances of objects (I call them tags). And I am implementing one of the classes as a Singleton.

The two classes for the Tagging system are defined as such:

#include "singleton.h"

class Tag: public bear::Singleton<Tag>
{
public:
    static dUINT32 RequestTag(Tagged* requester);
    static void RevokeTags(void);
private:
    Tag(void);
    ~Tag(void);

    Tagged** m_tagTable; // list of all objects with active tags
    dUINT32  m_tagTable_capacity, // the maximum capacity of the tag table
             m_tagIndexer; // last given tag
};

class Tagged
{
    friend class Tag;
public:
    inline dUINT32 GetTag(void) {return m_tag;}
private:
    inline void InvalidateTag(void) {m_tag=INVALID_TAG;}
    dUINT32 m_tag;
protected:
    Tagged();
    virtual ~Tagged();
};

The Singleton class is defined as such:

template <typename T>
class Singleton
{
public:
    Singleton(void);
    virtual ~Singleton(void);

    inline static T& GetInstance(void) {return (*m_SingletonInstance);}
private:
    // copy constructor not implemented on purpose
    // this prevents copying operations any attempt to copy will yield
    // a compile time error
    Singleton(const Singleton<T>& copyfrom);
protected:
    static T* m_SingletonInstance;
};

template <typename T>
Singleton<T>::Singleton (void)
{
    ASSERT(!m_SingletonInstance);
    m_SingletonInstance=static_cast<T*>(this);
}

template <typename T>
Singleton<T>::~Singleton (void)
{
    if (m_SingletonInstance)
        m_SingletonInstance= 0;
}

I am getting the following error upon trying to compile and link together the files:

test.obj : error LNK2001: unresolved external symbol "protected: static class util::Tag * bear::Singleton::m_SingletonInstance" (?m_SingletonInstance@?$Singleton@VTag@util@@@bear@@1PAVTag@util@@A) 1>C:...\tools\Debug\util.exe : fatal error LNK1120: 1 unresolved externals

Does anyone have any idea why I am getting this error?


回答1:


You should provide a definition for your static data member at namespace scope (currently, you only have a declaration):

template <typename T>
class Singleton
{
    // ...

protected:
    static T* m_SingletonInstance; // <== DECLARATION
};

template<typename T>
T* Singleton<T>::m_SingletonInstance = nullptr; // <== DEFINITION

If you are working with C++03, you can replace nullptr with NULL or 0.



来源:https://stackoverflow.com/questions/16554854/unresolved-external-symbol-in-singleton-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!