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.
这篇关于这个宏在类定义的开头有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:这个宏在类定义的开头有什么用?
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
