C++ dllimport静态数据成员的C++定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3491990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ definition of dllimport static data member
提问by MBZ
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?
我该怎么办?
回答by Anthony Williams
__declspec(dllimport)
means that the current code is usingthe DLL that implements your class. The member functions and static data members are thus defined in the DLL, and defining them again in your program is an error.
__declspec(dllimport)
表示当前代码正在使用实现您的类的 DLL。成员函数和静态数据成员因此在 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. In your header for MyClass
you then have:
为此使用宏是很常见的。在构建 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
{
...
};
This means that you can share the header between the DLL and the application that uses the DLL.
这意味着您可以在 DLL 和使用 DLL 的应用程序之间共享标头。
回答by liaK
From MSDN Documentation,
从MSDN 文档,
When you declare a class dllimport, all its member functions and static data members are imported. 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 时,它的所有成员函数和静态数据成员都会被导入。与 dllimport 和 dllexport 在非类类型上的行为不同,静态数据成员不能在定义 dllimport 类的同一程序中指定定义。
Hope it helps..
希望能帮助到你..
回答by user396672
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