C预处理器宏扩展 [英] C preprocessor macro expansion

查看:104
本文介绍了C预处理器宏扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下情况下,我很难理解C预处理程序如何应用重写规则.我有以下宏:

I have difficulty understanding how rewriting rules are applied by the C preprocessor in the following context. I have the following macros:

#define _A(x) "A" _##x
#define _B(x) "B" _##x
#define X(x) _##x

这个想法是,这些宏中的每一个都使用串联来创建一个新表达式,它本身可以是一个宏-如果是宏,我希望将其扩展:

The idea is that each of these macros uses the concatenation to create a new expression, which can itself be a macro — if its a macro, I'd like it to be expanded:

现在,以下内容将按照我的期望进行扩展:

Now, the following expands just like I expect:

X(x)       expands to _x
X(A(x))    expands to "A" _x
X(A(B(x))) expands to "A" "B" _x

但是,一旦再使用一次同一个宏,扩展就会停止:

However, once the same macro is used more then once, the expansion stops:

X(A(A(x)))       expands to "A" _A(x), expected "A" "A" _x
X(B(B(x)))       expands to "B" _B(x), expected "B" "B" _x
X(A(B(A(x))))    expands to "A" "B" _A(x), expected "A" "B" "A" _x 
X(A(B(A(B(x))))) expands to "A" "B" _A(B(x)), expected "A" "B" "A" "B" _x 

我猜这里有某种只能扩展同名宏一次"的规则在起作用吗?我可以做些什么来使宏扩展我想要的方式吗?

I guess that there is some sort of "can expand same-named macro only once" rule at play here? Is there something I can do to get the macros to expand the way I want?

推荐答案

C99草案说,在宏扩展中不允许递归:

C99 draft says that there's no recursion permitted in macro expansion:

6.10.3.4重新扫描并进一步替换

  1. 替换替换列表中的所有参数后, ###处理已经进行,所有的地标预处理令牌都已删除.产生的预处理令牌序列 然后重新扫描,以及所有后续预处理 源文件的令牌,以便替换更多的宏名称.
  2. 如果 在扫描此文件的过程中找到了要替换的宏的名称 替换列表(不包括源文件的其余部分 预处理令牌),它不会被替换.此外,如果有的话 嵌套替换遇到要替换的宏的名称,它 不被替换.这些不可替换的宏名称预处理 令牌不再可用于进一步替换,即使它们 稍后在该宏名称的上下文中进行(重新)检查 否则,预处理令牌将被替换.
  1. After all parameters in the replacement list have been substituted and # and ## processing has taken place, all placemarker preprocessing tokens are removed. The resulting preprocessing token sequence is then rescanned, along with all subsequent preprocessing tokens of the source file, for more macro names to replace.
  2. If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Furthermore, if any nested replacements encounter the name of the macro being replaced, it is not replaced. These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced.

所以X(A(A(x)))扩展为"A" _A(x),但是扩展本身并没有扩展,如您所见.

So X(A(A(x))) expands to "A" _A(x), but that expansion is not itself expanded, as you've seen.

这篇关于C预处理器宏扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆