What is this macro for at the beginning of a class definition?(这个宏在类定义的开头有什么用?)
问题描述
我正在查看一个库的源代码,许多类是使用以下形式定义的
I'm looking through the source of a library and many classes are defined using the following form
class THING_API ClassName
{
...
跳转到宏定义...
#ifndef THING_API
#define THING_API /**< This macro is added to all public class declarations. */
#endif
这有什么用,它是一种常见的技术吗?
What could this be for, and is it a common technique?
推荐答案
它看起来很像导出宏,在 Windows 上构建共享库 (.dll) 时需要它.使用 MSVC 编译时,您必须在构建库时将 __declspec(export)
放在该位置,在构建其客户端时将 __declspec(import)
放在该位置.这是这样实现的:
It looks to me very much like export macro, which is required when building a shared library (.dll) on Windows. When compiling with MSVC, You have to put __declspec(export)
in that spot when building a library, and __declspec(import)
when building its client. This is achieved like so:
#if COMPILING_DLL
#define THING_API __declspec(dllexport)
#else
#define THING_API __declspec(dllimport)
#endif
然后您为库项目定义COMPILING_DLL
,并为所有其他项目保留未定义.如果您不在 Windows 上或编译静态库,则需要将其定义为空白,就像在您的问题中所做的那样.
Then you define COMPILING_DLL
for the library project, and leave it undefined for all other projects. And if you're not on Windows or compiling a static library, you need to define it blank like it's done in your question.
P.S.其他Windows编译器使用自己的关键字代替__declspec(dllimport)
,但原理不变.
P. S. Other Windows compilers use their own keywords instead of __declspec(dllimport)
, but the principle remains.
这篇关于这个宏在类定义的开头有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:这个宏在类定义的开头有什么用?


基础教程推荐
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 这个宏可以转换成函数吗? 2022-01-01