将宏替换为C中的宏 [英] Substituting macros within macros in C
问题描述
我正在尝试使代码段可重用.我下面的评论片段没有按照我的意愿做:
I'm trying to make a code-section reusable. My comment snippet below isn't doing what I want it to:
#define NAME ABC
#define LOG_SIZE NAME##_LEN
我希望 LOG_SIZE
解析为 ABC_LEN
.我曾尝试使用#号,但未能使其正常工作. LOG_SIZE
在所有代码中都被使用,所以我不想将宏更改为:
I would like LOG_SIZE
to resolve to ABC_LEN
. I've tried playing around with the #'s, but haven't been able to get this to work. LOG_SIZE
is used all over the code, so I don't want to change the macro to:
#define LOG_SIZE(name)名称## _ LEN
有没有办法做到这一点?
Is there a way to do this?
推荐答案
问题在于,如果宏参数将被字符串化或连接到另一个标记,则它们不会自动扩展.
The problem is that macro arguments aren't automatically expanded if they would be stringified or concatenated to another token.
C99 6.10.3.1/1:
C99 6.10.3.1/1:
在识别了调用类似函数的宏的参数之后,将进行参数替换.除非包含在其中的所有宏都已扩展,否则替换列表中的参数(除非在#或##预处理令牌之前或在##预处理令牌之后(请参见下文))被相应的参数替换.在被替换之前,每个参数的预处理令牌都被完全替换为宏,就好像它们构成了其余的预处理文件一样;没有其他预处理令牌可用.
After the arguments for the invocation of a function-like macro have been identified, argument substitution takes place. A parameter in the replacement list, unless preceded by a # or ## preprocessing token or followed by a ## preprocessing token (see below), is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced as if they formed the rest of the preprocessing file; no other preprocessing tokens are available.
您可以通过在传递 NAME
的宏和将其与 _LEN
串联的宏之间添加另一个宏来解决此问题.
You can get around this by adding another macro in between the one that passes NAME
and the one that concatenates it with _LEN
.
#define NAME ABC
#define AFTERX(x) x##_LEN
#define XAFTERX(x) AFTERX(x)
#define LOG_SIZE XAFTERX(NAME)
LOG_SIZE
//evaluates to ABC_LEN
如果您有好奇心,可以在第3.10节中详细了解gcc手册..6:参数预扫描
The gcc manual goes into further detail if you're curious, in Section 3.10.6: Argument Prescan
这篇关于将宏替换为C中的宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!