dllimport静态数据成员的C++定义

MBZ*_*MBZ 18 c++ dll static static-members

我有一个类如下所示:

//.h file
class __declspec(dllimport) MyClass
{
    public:
    //stuff
    private:

    static int myInt;
};

// .cpp file
int MyClass::myInt = 0;
Run Code Online (Sandbox Code Playgroud)

我得到以下编译错误:

error C2491: 'MyClass::myInt' : definition of dllimport static data member not allowed
Run Code Online (Sandbox Code Playgroud)

我该怎么办?

Ant*_*ams 30

__declspec(dllimport)表示当前代码正在使用实现您的类的DLL.因此,在DLL中定义成员函数和静态数据成员,并在程序中再次定义它们是一个错误.

如果您正在尝试编写实现此类的DLL的代码(从而定义成员函数和静态数据成员),那么您需要标记该类__declspec(dllexport).

为此通常使用宏.构建DLL时,您可以定义宏BUILDING_MYDLL或类似的.在你的标题中,MyClass你有:

    #ifdef _MSC_VER
    #  ifdef BUILDING_MYDLL
    #    define MYCLASS_DECLSPEC __declspec(dllexport)
    #  else
    #    define MYCLASS_DECLSPEC __declspec(dllimport)
    #  endif
    #endif

    class MYCLASS_DECLSPEC MyClass
    {
        ...
    };
Run Code Online (Sandbox Code Playgroud)

这意味着您可以共享DLL与使用DLL的应用程序之间的标头.


lia*_*iaK 6

MSDN 文档

当你声明一个类 dllimport 时,它的所有成员函数和静态数据成员都会被导入。与 dllimport 和 dllexport 在非类类型上的行为不同,静态数据成员不能在定义 dllimport 类的同一程序中指定定义

希望能帮助到你..