C++ Error linking in consumer file caused by static data field

房东的猫 提交于 2019-12-13 02:06:28

问题


I want to use a static global variable as a mutex. When I try to compile the following code:

//header file

class __declspec(dllexport) StateConservator
{
private:
    StateConservator();
    StateConservator(const StateConservator&);

protected:
    const CString m_oldConf;
    CContainer& m_container;
    static bool x_mutex;
public:
    StateConservator(CContainer& container, const CString& conf)
        : m_container(container)
        , m_oldConf(!x_mutex? container.GetConf():_T(""))
    {
        if(!x_mutex)
        {
            x_mutex= true;
            m_container.SetConf(conf);
        }
    }

    ~StateConservator()
    {
        if(x_mutex)
        {
            x_mutex= false;
            m_container.SetConf(m_oldConf);
        }
    }
};


//cpp file
bool StateConservator::x_mutex= false;


//consumer file
StateConservator cs(*pContainer, pDoc->GetConfiguration());

I get the error:

Consumer.obj : error LNK2001: unresolved external symbol "protected: static bool StateConservator::x_mutex" (?x_mutex@StateConservator@@1_NA)

Please, how can I solve the problem?

UPDATE

I created two minimal programs containing only the essential part to test the problem and they work! This is getting even more strange!

UPDATE 2

Notice the __declspec(dllexport) declaration after the class, that was missing.


回答1:


Sorry, people.

I was defining the code of StateConservator in a file belonging to the project. But after I realized it would make more sense in another file.

I was not realizing the second file was part of another solution. So, I did not compile the second solution, hence the error.

I think I need an extension to Visual Studio to colorize the tabs of other projects with another color. If somebody knows about one, I will appreciate.

Thanks for supporting the annoyance caused by me.

UPDATE

Notice the __declspec(dllexport) declaration after the class, that was missing.



来源:https://stackoverflow.com/questions/29106134/c-error-linking-in-consumer-file-caused-by-static-data-field

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