简体   繁体   English

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

[英]C++ definition of dllimport static data member

I do have a class which looks like below: 我有一个类如下所示:

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

    static int myInt;
};

// .cpp file
int MyClass::myInt = 0;

I get the following compile error: 我得到以下编译错误:

error C2491: 'MyClass::myInt' : definition of dllimport static data member not allowed

what should I do? 我该怎么办?

__declspec(dllimport) means that the current code is using the DLL that implements your class. __declspec(dllimport)表示当前代码正在使用实现您的类的DLL。 The member functions and static data members are thus defined in the DLL, and defining them again in your program is an error. 因此,在DLL中定义成员函数和静态数据成员,并在程序中再次定义它们是一个错误。

If you are trying to write the code for the DLL that implements this class (and thus defines the member functions and static data members) then you need to mark the class __declspec(dllexport) instead. 如果您正在尝试编写实现此类的DLL的代码(从而定义成员函数和静态数据成员),则需要标记类__declspec(dllexport)

It is common to use a macro for this. 为此通常使用宏。 When building your DLL you define a macro BUILDING_MYDLL or similar. 构建DLL时,您可以定义一个宏BUILDING_MYDLL或类似的。 In your header for MyClass you then have: MyClass的标题中,您可以:

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

    class MYCLASS_DECLSPEC MyClass
    {
        ...
    };

This means that you can share the header between the DLL and the application that uses the DLL. 这意味着您可以共享DLL与使用DLL的应用程序之间的标头。

From MSDN Documentation , MSDN文档

When you declare a class dllimport, all its member functions and static data members are imported. 声明类dllimport时,将导入其所有成员函数和静态数据成员。 Unlike the behavior of dllimport and dllexport on nonclass types, static data members cannot specify a definition in the same program in which a dllimport class is defined . 与dllimport和dllexport在非类类型上的行为不同, 静态数据成员不能在定义dllimport类的同一程序中指定定义

Hope it helps.. 希望能帮助到你..

if you are importing a class you are importing it with all it members so it is impossible to define any class member on the "client side". 如果你要导入一个类,你要用它的所有成员导入它,所以不可能在“客户端”定义任何类成员。 dllexport keyword should be used on behalf of implementation dll dllexport关键字应该代表实现dll使用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM