错误 C2491:不允许定义 dllimport 函数

新手上路,请多包涵

我在 Visual Studio 2013 上制作 dll 时遇到问题。此代码适用于 Code::Blocks。错误是 definition of dllimport function not allowed" on line void DLL_EXPORT prim(map<string, vector<int>> nodes, map<pair<string, string>, pair<int, string>> edges) 。如何解决?

 main.h:
#ifndef __MAIN_H__
#define __MAIN_H__

#include <windows.h>
#include <iostream>
#include <vector>
#include <map>

using namespace std;

#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport)
#else
    #define DLL_EXPORT __declspec(dllimport)
#endif

#ifdef __cplusplus
extern "C"
{
#endif

void DLL_EXPORT prim( map<string,vector<int>> nodes, map<pair<string,string>,pair<int,string>> edges);

#ifdef __cplusplus
}
#endif

#endif // __MAIN_H__

第二个文件:

 main.cpp:
#include "main.h"
//some other includes

// a sample exported function

extern "C"
{
    void DLL_EXPORT prim(map<string, vector<int>> nodes, map<pair<string, string>, pair<int, string>> edges)
    {
        //some code
    }
}

我试图修复它,但我没有更多的想法。当我将第二个文件中的 prim 函数从定义更改为声明时,dll 编译没有错误,但没有负责算法实现的代码。

感谢所有回复。

编辑:

我将临时 #define BUILD_DLL 添加到 main.h 中,然后在 Cmake 中添加,我可以工作了。感谢您的回复。

原文由 pawel112 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 3k
2 个回答

main.hmain.cpp 将用于您正在创建的 DLL 项目中。

只有 main.h 将用于访问您创建的 DLL 的客户端可执行文件/DLL。

因此,DLL 项目的 main.h 需要 __declspec(dllexport) 。这样就可以从DLL中导出函数。所以,在 DLL Project's Properties -> C/C++ -> 'Preprocessor definitions' 中定义 BUILD_DLL

main.h 客户端可执行文件需要 __declspec(dllimport) 。这样就可以从DLL中导入函数。所以 不需要Executable Project's Properties -> C/C++ -> 'Preprocessor definitions' 中定义 BUILD_DLL

原文由 sameerkn 发布,翻译遵循 CC BY-SA 3.0 许可协议

您应该只定义 BUILD_DLL 是您的一些标题或项目属性 - > C/C++ - > ‘预处理器定义’。所以 DLL_EXPORT 将是 __declspec(dllexport) 这就是你在构建你的 dll 时想要的。 __declspec(dllimport) 如果要从其他 dll 导入函数,则需要。这个错误意味着你不能重新定义导入的函数,因为它是在你导入它的 dll 中定义的。

原文由 russtone 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题