c++ - 使用 dllimport 代替 dllexport

标签 c++ dll dllimport dllexport declspec

在 Visual Studio 2015 中构建我的 dll 时,我似乎可以交替使用 __declspec(dllexport)__declspec(dllimport)。 DLL 需要 dllexport 命令,但似乎 dllexportdllimport 就足够了。我有以下头文件声明一个简单的添加() 函数:

添加.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,因为这是最合理的错误解决方案。

treat compiler warnings as errors 是个好习惯.

关于c++ - 使用 dllimport 代替 dllexport,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58138630/

相关文章:

c++ - 为什么这段代码的输出是fffffff9?

c++ - 在 C++ 中查找序列中的第 N 项

c++ - 如何在凯撒密码破译作业中使用英语字母频率?

java - JDBC 中缺少 dll

delphi - 从 Delphi 代码调用 Visual C++ DLL 的函数

vba - 对 Excel Vba 中的 DLL 函数调用进行故障排除

c++ - 如何为服务器运行 valgrind?

c# - 如何将 MySQL.Data 与我的 ClickOnce 应用程序打包在一起?

c# - 从 C# 设置非托管 C dll 的公共(public)字段

c# - 使用 DllImport 在 C# 中调用 OpenGL 函数?