使用dllimport代替dllexport [英] Using dllimport in place of dllexport
问题描述
在构建dll时,我似乎可以互换使用 __ declspec(dllexport)
和 __ declspec(dllimport)
在Visual Studio 2015中。在制作DLL时,我会想到需要 dllexport
命令,但似乎 dllexport
或 dllimport
就足够了。我有以下头文件声明了一个简单的add()函数:
I seem to be able to use __declspec(dllexport)
and __declspec(dllimport)
interchangeably when building my dll in Visual Studio 2015. I would have thought when making the DLL that the dllexport
command would have been required but it seems either dllexport
or dllimport
is adequate.I have the following header file declaring a simple add() functions:
add .h
#pragma once
#ifdef ADDDLL_EXPORTS
#define ADDDLL_API __declspec(dllexport)
#else
#define ADDDLL_API __declspec(dllimport)
#endif
ADDDLL_API int add(int x, int y);
在cpp文件中具有以下定义:
with the following definition in a cpp file:
add.cpp
#include "add.h"
int add(int x, int y)
{
return x + y;
}
无论 ADDDLL_EXPORTS
是否在配置属性>预处理程序>预处理程序定义中定义。例如,在一个包含.lib文件作为附加依赖项的单独项目中(配置属性>链接器>输入>附加依赖项),我运行了以下代码
I seem to be able to use the built DLL whether ADDDLL_EXPORTS
is defined or not in Configuration Properties > Preprocessor > Preprocessor Definitions. For example, in a separate project which includes the .lib file as an additional dependency (Configuration Properties > Linker > Input > Additional Dependencies), I have the following code that runs
main.cpp
#include <iostream>
#include "add.h"
int main()
{
int sum = add(4, 5);
std::cout << "sum = " << sum << std::endl;
std::system("pause");
return 0;
}
任何见解都值得赞赏。让我知道是否需要更多信息。
Any insight appreciated. Let me know if more information is needed. Thanks in advance!
推荐答案
如果仔细看,您将看到DLL项目使用 warnings 编译。 >,像这样:
If you look carefully, you will see that your DLL project compiles with warnings, like this:
c:\yourproject\add.cpp(3,1):warning C4273: 'add': inconsistent dll linkage
编译器知道您无能为力。 dllimport
函数不应定义,只能声明。因此,当编译器看到该定义时,它假定应改为使用 dllexport
,因为这是错误的最合理解决方案。
The compiler knows that you are up to no good. A dllimport
function should not be defined, only declared. So when the compiler sees the definition, it assumes dllexport
should be used instead, because that's the most reasonable resolution of the mistake.
这篇关于使用dllimport代替dllexport的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!