windows cpp文件中是否需要__declspec(dllexport)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/557317/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 11:59:39  来源:igfitidea点击:

Is __declspec(dllexport) needed in cpp files

c++windowsdll

提问by Zitrax

Probably a simple question but I only have Linux to test this code on where __declspec(dllexport) is not needed. In the current code __declspec(dllexport) is in front of all files in the .h file but just in front of like 50% of the functions in the cpp file so I am wondering if they are really needed in the cpp file at all ?

可能是一个简单的问题,但我只有 Linux 可以在不需要 __declspec(dllexport) 的地方测试此代码。在当前代码中 __declspec(dllexport) 位于 .h 文件中的所有文件之前,但位于 cpp 文件中 50% 的函数之前,所以我想知道它们是否真的在 cpp 文件中需要?

回答by Doug T.

No, its only needed in the header.

不,它只在标题中需要。

Here's a linkwith more info.

这是包含更多信息的链接

Expanding on what Vinay was saying, I've often seen a macro defined

扩展 Vinay 所说的内容,我经常看到一个宏定义

#if defined(MODULENAME_IMPORT)
#define EXPORTED __declspec(dllimport)
#elif defined(MODULENAME_EXPORT)
#define EXPORTED __declspec(dllexport)
#endif

Then in your header you do

然后在你的标题中你做

void EXPORTED foo();

set the defines accordingly in the project settings for the project doing the import/exporting.

在执行导入/导出的项目的项目设置中相应地设置定义。

回答by Vinay

No, it is not required in cpp file. Only in declaration it is required.

不,cpp 文件中不需要它。仅在声明中是必需的。

For Example if I have a class CMyClass. If I want to export this then .h will have

例如,如果我有一个类 CMyClass。如果我想导出这个,那么 .h 将有

.h Server code

.h 服务器代码

__declspec(dllexport) CMyClass { };

__declspec(dllexport) CMyClass { };

In the client code i.e., which uses this class you have to forward declare the class as

在使用此类的客户端代码 ie 中,您必须转发声明该类为

Client code

客户端代码

__declspec(dllimport) CMyClass;

__declspec(dllimport) CMyClass;

// Code to use the class

// 使用类的代码

回答by Ketan

You may use in .cpp file also when you have templated code and you are instantiating in .cpp file then you need to export the definition when it is instantiated. But even in this case, I have seen that doing in .h also works. On windows you can use dumpbin.exe /exports *.dll to see what signatures are exported, there is similar utility in Linux too. This will give you an idea how signature is exported.

您也可以在 .cpp 文件中使用模板代码并且在 .cpp 文件中实例化,然后在实例化时需要导出定义。但即使在这种情况下,我也看到在 .h 中这样做也有效。在 Windows 上,您可以使用 dumpbin.exe /exports *.dll 来查看导出了哪些签名,Linux 中也有类似的实用程序。这将使您了解签名是如何导出的。