C++ 静态数据字段导致的使用者文件中的链接错误

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

本文关键字:使用者 文件 链接 错误 静态 数据 字段 C++      更新时间:2023-10-16

我想使用静态全局变量作为互斥锁。当我尝试编译以下代码时:

//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());

我收到错误:

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

请问,我该如何解决问题?

更新

我创建了两个最小的程序,只包含测试问题的基本部分,它们可以工作!这越来越奇怪了!

更新 2

请注意类后面缺少的 __declspec(dllexport) 声明。

对不起,人们。

我正在属于该项目的文件中定义StateConservator的代码。但是在我意识到在另一个文件中会更有意义之后。

我没有意识到第二个文件是另一个解决方案的一部分。因此,我没有编译第二个解决方案,因此出现了错误。

我想我需要Visual Studio的扩展,用另一种颜色为其他项目的选项卡着色。如果有人知道一个,我将不胜感激。

感谢您支持我造成的烦恼。

更新

请注意类后面缺少的 __declspec(dllexport) 声明。