这个宏在类定义的开头有什么用?

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.

这篇关于这个宏在类定义的开头有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:这个宏在类定义的开头有什么用?

基础教程推荐