gpt4 book ai didi

C 预处理器宏扩展限制,使用带参数的叠层宏

转载 作者:太空宇宙 更新时间:2023-11-04 03:18:46 24 4
gpt4 key购买 nike

我在 gcc 项目中制作了一些宏来帮助我设计对话框的小部件。但是我遇到了编译错误,所以我做了以下测试:

#define XPOS_ISAFTER(obj) (obj##_XPOS + obj##_XSIZE)

#define PMD_TUTU_XPOS 10
#define PMD_TUTU_XSIZE 10

#define PMD_TUTU2_XPOS XPOS_ISAFTER(PMD_TUTU)
#define PMD_TUTU2_XSIZE 20

#define PMD_TUTU3_XPOS XPOS_ISAFTER(PMD_TUTU2)


int main(void){
int i = 0;
printf("Hello World!\n");
fflush(stdout);

/* Infinite loop */
while (1)
{
i += PMD_TUTU2_XPOS;
i += PMD_TUTU3_XPOS;
}

return 0;
}

当询问预处理器输出时,我得到以下信息:

839 int main(void){
840 int i = 0;
841 printf("Hello World!\n");
842 fflush(stdout);
843
844
845 while (1)
846 {
847 i += (10 + 10);
848 i += (XPOS_ISAFTER(PMD_TUTU) + 20);
849 }
850
851 return 0;

我搜索了一些建议tricks强制重新扫描,没有任何结果。所以预处理器不扩展这个递归宏?

最佳答案

问题不是预处理器无法重新扫描,而是当它重新扫描时,它拒绝在先前扩展(间接)产生的文本中扩展 XPOS_IS_AFTER() 宏的外观同一个宏。换句话说,预处理器不支持宏递归。这是由标准明确规定的:

[When rescanning a macro's replacement text,] 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.

( C2011, 6.10.3.4/2 )

GCC 对您的代码完全按照它应该做的去做。您需要一个不同的计划。

关于C 预处理器宏扩展限制,使用带参数的叠层宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48670362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com