windows 使用dllimport程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4644758/
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
Using dllimport procedure
提问by Ramy
I am trying to write a dll,this is how looks my header file:
我正在尝试编写一个 dll,这是我的头文件的外观:
#ifndef _DLL_H_
#define _DLL_H_
#if BUILDING_DLL
# define DLLIMPORT __declspec (dllexport)
#else /* Not BUILDING_DLL */
# define DLLIMPORT __declspec (dllimport)
#endif /* Not BUILDING_DLL */
DLLIMPORT void HelloWorld (void);
#endif /* _DLL_H_ */
In the .cpp file I include this header file,and I try declaring a dll import procedure this way:
在 .cpp 文件中,我包含了这个头文件,并尝试以这种方式声明一个 dll 导入过程:
DLLIMPORT void HelloWorld ()
{
MessageBox (0, "Hello World from DLL!n", "Hi", MB_ICONINFORMATION);
}
But the compiler ( I have mingw32 on windows 7 64 bit) keeps giving me this error:
但是编译器(我在 Windows 7 64 位上有 mingw32)不断给我这个错误:
E:\Cpp\Sys64\main.cpp|7|error: function 'void HelloWorld()' definition is marked dllimport|
E:\Cpp\Sys64\main.cpp||In function 'void HelloWorld()':|
E:\Cpp\Sys64\main.cpp|7|warning: 'void HelloWorld()' redeclared without dllimport attribute: previous dllimport ignored|
||=== Build finished: 1 errors, 1 warnings ===|
And I don't understand why.
我不明白为什么。
回答by harper
The declspec(dllimport)
generates entries in the module import table of the module. This import table is used to resolve the referneces to the symbols at link time. At load time these references are fixed by the loader.
将declspec(dllimport)
在模块的模块导入表生成条目。此导入表用于在链接时解析对符号的引用。在加载时,这些引用由加载器固定。
The declspec(dllexport)
generates entries in the DLL export table of the DLL. Further you need to implement symbols (function, variables) that are declare with it.
该declspec(dllexport)
DLL中的DLL导出表生成条目。此外,您需要实现用它声明的符号(函数、变量)。
Since you you implement the DLL, you must define BUILDING_DLL. This could be done with #define
but this should be better set in the project settings.
由于您实现了 DLL,因此您必须定义 BUILDING_DLL。这可以完成,#define
但这应该在项目设置中更好地设置。
回答by jwav
I had the exact same error before realizing that I didn't actually define BUILDING_DLL
.
在意识到我实际上并没有定义BUILDING_DLL
.
Therefore, DLLIMPORT
was defined as __declspec (dllimport)
and not __declspec (dllexport)
as it was intended. After I defined the symbol, the problem was solved.
因此,DLLIMPORT
被定义为__declspec (dllimport)
而不是__declspec (dllexport)
如其所愿。我定义了符号后,问题就解决了。
Since you're on MinGW, you need to pass the following:
由于您在 MinGW 上,您需要通过以下内容:
-DBUILDING_DLL
as a compiler option, or simply add
作为编译器选项,或者简单地添加
#define BUILDING_DLL
at the top of your file. The former is better, only use the #define solution if you can't figure out how to pass the -DBUILDING_DLL
option to gcc.
在文件的顶部。前者更好,如果您不知道如何将-DBUILDING_DLL
选项传递给 gcc ,请仅使用 #define 解决方案。