c++ - 如何避免cpp给宏参数加空格

标签 c++ gcc macros

我公司有 1000 多个使用宏指定包含路径的源文件。我无法更改它,它适用于当前的编译器。现在,我尝试用 GCC(4.8.2 或 3.4.6)编译它,但它失败了。

基本上有这样一个宏:

#define COMP_INC(comp, file) <comp/include/file>

就是这样使用的:

#include COMP_INC(posix, inttypes.h)

我的问题是 GCC 出于某种未知原因将我的宏调用转换为:

#include <posix/include/ inttypes.h>

注意到“inttypes.h”之前的空格了吗?因此,找不到头文件。

为什么预处理器要插入一个空格?我可以避免吗?我只能更改宏,不能更改使用它的源文件。

最佳答案

删除 posixinttypes.h 之间的空格(逗号后)。问题消失了。

answer告诉我们为什么会这样:

From the C99 standard:

A preprocessing directive of the form

# define identifier replacement-list new-line

defines an object-like macro that causes each subsequent instance of the macro name to be replaced by the replacement list of preprocessing tokens that constitute the remainder of the directive.


So macros work on tokens and the whitepace is to be expected.

编辑:

根据这个answer ,您可以使用 traditional-cpp 标志来模仿不添加空格的旧行为。我不确定这将如何影响您的构建,但您可以尝试一下:

Only much older preprocessors didn't insert that extra space -- note that original entry was submitted over 20 years ago in 1988, before the 1989 version of the C standard was standardized. You can pass the -traditional-cpp flag to the GCC preprocessor, which causes it to imitate the behavior of old-fashioned C preprocessors, as opposed to ISO C preprocessors.

关于c++ - 如何避免cpp给宏参数加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23245649/

相关文章:

c++ - 无法在 Linux 上找到 SDL2_gfx 库

检查特定 gcc 编译器的 glibc 版本

c++ - 使用 Eclipse 检查 GCC 版本

vb.net - 如何使用 Visual Studio 宏运行 TFS 工作项查询

c - 错误的宏定义导致 "Expected expression"错误

c++ - 以位计数递增顺序遍历整数的每个位掩码

c++ - CMake 从公共(public)源代码树生成多个项目的方法

C++ : When is a declared variable is initialized without assigning it to any value?

C++如何使用less条件语句?

iphone - 如何为 "oneOf"编写函数或宏...在可变参数中进行转换?