Unresolved external symbol on static class members

后端 未结 5 1481
温柔的废话
温柔的废话 2020-11-22 02:04

Very simply put:

I have a class that consists mostly of static public members, so I can group similar functions together that still have to be called from other clas

5条回答
  •  生来不讨喜
    2020-11-22 02:52

    in my case, I declared one static variable in .h file, like

    //myClass.h
    class myClass
    {
    static int m_nMyVar;
    static void myFunc();
    }
    

    and in myClass.cpp, I tried to use this m_nMyVar. It got LINK error like:

    error LNK2001: unresolved external symbol "public: static class... The link error related cpp file looks like:

    //myClass.cpp
    void myClass::myFunc()
    {
    myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
    }
    

    So I add below code on the top of myClass.cpp

    //myClass.cpp
    int myClass::m_nMyVar; //it seems redefine m_nMyVar, but it works well
    void myClass::myFunc()
    {
    myClass::m_nMyVar = 123; //I tried to use this m_nMyVar here and got link error
    }
    

    then LNK2001 is gone.

提交回复
热议问题