C中的计算包含

标签 c macros header-files

我正在阅读 gnu.org 上有关计算包含的 C 预处理器指南页面,其中有以下解释:

2.6 Computed Includes

Sometimes it is necessary to select one of several different header files to be included into your program. They might specify configuration parameters to be used on different sorts of operating systems, for instance. You could do this with a series of conditionals,

#if SYSTEM_1
# include "system_1.h"
#elif SYSTEM_2
# include "system_2.h"
#elif SYSTEM_3 …
#endif

That rapidly becomes tedious. Instead, the preprocessor offers the ability to use a macro for the header name. This is called a computed include. Instead of writing a header name as the direct argument of ‘#include’, you simply put a macro name there instead:

#define SYSTEM_H "system_1.h" 
…
#include SYSTEM_H

这对我来说没有意义。第一个代码片段通过使用 if elifs 分支允许基于您遇到的系统类型的可选性。第二个似乎没有可选性,因为宏用于定义特定的系统类型,然后宏被放入 include 语句中,没有任何代码暗示可以更改其定义。然而,文本暗示它们是等价的,并且第二个是第一个的简写。谁能解释第一个代码片段的可选性如何存在于第二个代码片段中?我也不知道第二个代码片段中的“...”隐含了哪些代码。

最佳答案

代码或构建系统中的其他一些地方定义或不定义条件中正在测试的宏。建议的是,与其在那些地方定义许多不同的 SYSTEM_1SYSTEM_2 等宏,不如将 SYSTEM_H 定义为值这是我们想要的。

很可能这实际上不会在显式 #define 中,而是在编译器选项中,例如

gcc -DSYSTEM_H='"system_1.h"' ...

这很可能实际上来自 makefile 或其他配置文件中的设置。

关于C中的计算包含,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48028658/

相关文章:

更改 C 函数参数中错误检查的类型?

Ubuntu 13.10 中的 C 编译错误,可能是 makefile 中的错误

c - postgresql:时区 "localtime"无法识别

haskell - 是否有可能在 Lisp 中使用宏来实现依赖类型的好处?

C 通用宏名称 - gcc -fextended-identifiers

c++ - 在头文件中映射c++

arrays - Arduino Sketch - 头文件中的对象不包含任何值

c++ - 包含 LPCTSTR 的函数

macros - Racket /方案 - 语法案例

c++ - g++ 找不到 header ,但我确实包含了它们