C 预编译中的二次替换问题

本文详细解析了C预编译过程中二次替换问题的原理与应用,通过实例展示了如何利用双层宏实现深入替代,以及宏替换时的二次扫描机制。深入理解这一过程对于优化代码和提高编译效率至关重要。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C 预编译中的二次替换问题

 

今天在阅读linux看门狗驱动的时候,发现一段奇怪的代码:

 

static int tmr_atboot       = CONFIG_S3C2410_WATCHDOG_ATBOOT;

MODULE_PARM_DESC(tmr_atboot,

              "Watchdog is started at boot time if set to 1, default="

                     __MODULE_STRING(CONFIG_S3C2410_WATCHDOG_ATBOOT));

 

依次跟进去宏的具体定义:

       #define __MODULE_STRING(x) __stringify(x)

       #define __stringify_1(x...)    #x

#define __stringify(x...) __stringify_1(x)

 

这里一共使用了三处宏,分别是:__MODULE_STRING(x)、__stringify_1(x...)、__stringify(x...)。似乎这里的宏非常冗余。

 

GNU CPP Manual中是这样指出来的:

    Macro arguments are completely macro-expanded before they are substituted into a macro body, unless they are stringified or pasted with other tokens. After substitution, the entire macro body, including the substituted arguments, is scanned again for macros to be expanded. The result is that the arguments are scanned twice to expand macro calls in them.

上面的总体意思就是:二次替换的问题。

 

具体使用例子来说明:

Main1.c

#include <stdio.h>

#define BUF_SIZE abc

#define __stringify(x) #x

Int main()

{

    Printf(“%s\n”, __stringify(BUF_SIZE));

    Return 0;

}

结果为: BUF_SIZE

Main2.c

#include <stdio.h>

#define BUF_SIZE abc

#define __stringify(x)  __stringify_1(x)

#define __stringify_1(x)  #x

Int main()

{

    Printf(“%s\n”, __stringify(BUF_SIZE));

    Return 0;

}

结果为: abc

总结,在宏替换时,如果出现标识字符串或者字符串连接的情况出现(“#”、“##”),那么宏替换会被截断,这个时候我们可以通过双层宏来完成深入替代的任务。

 

转载于:https://www.cnblogs.com/wenhuisun/archive/2012/07/06/2578998.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值