在 Visual Studio 2015 中构建我的 dll 时,我似乎可以交替使用 __declspec(dllexport)
和 __declspec(dllimport)
。 DLL 需要 dllexport
命令,但似乎 dllexport
或 dllimport
就足够了。我有以下头文件声明一个简单的添加() 函数:
添加.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文件中定义如下:
添加.cpp
#include "add.h"
int add(int x, int y)
{
return x + y;
}
无论 ADDDLL_EXPORTS
是否在 Configuration Properties > Preprocessor > Preprocessor Definitions 中定义,我似乎都能够使用构建的 DLL。例如,在一个包含 .lib 文件作为附加依赖项的单独项目中(配置属性 > 链接器 > 输入 > 附加依赖项),我有以下运行的代码
主要.cpp
#include <iostream>
#include "add.h"
int main()
{
int sum = add(4, 5);
std::cout << "sum = " << sum << std::endl;
std::system("pause");
return 0;
}
任何见解表示赞赏。让我知道是否需要更多信息。提前致谢!
最佳答案
如果仔细观察,您会看到您的 DLL 项目编译时带有警告,如下所示:
c:\yourproject\add.cpp(3,1):warning C4273: 'add': inconsistent dll linkage
编译器知道你不怀好意。 dllimport
函数不应被定义,而只能被声明。因此,当编译器看到定义时,它假定应该使用 dllexport
,因为这是最合理的错误解决方案。
关于c++ - 使用 dllimport 代替 dllexport,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58138630/