确定 C 宏的扩展

Determine the expansion of a C macro

有没有办法通过检查编译对象或通过 运行 .c 或 .h 文件上的某种形式的 gcc -E 来确定扩展 C 宏的 "final value"?

test.h

#define AAA 1
#define BBB 10
#define CCC (AAA+BBB)

test.c

#include <stdio.h>
#include "test.h"

int main(){
   printf("%d\n", CCC);
   return 0;
}

因此有没有办法获得扩展值:

#define CCC 11

#define CCC (1+10)

如果用

编译
gcc -dM -E test.c | grep CCC 

gcc -dD -E test.c | grep CCC

产出

#define CCC (AAA+BBB)

这需要我仍然知道 AAABBB 是什么。

编译:

gcc -E test.c

给出(跳过样板):

# 4 "test.c"
int main(){
printf("%d\n", (1+10));
return 0;
}   

虽然它扩展了 CCC,但我现在已经失去了回到 CCC 的映射。

编辑: 目前还不清楚,我想要的是确定 CCC 是什么(11 或 1+10(如 gcc -E 示例显示它只插入(1+10)而不是 11),最好不改变代码本身. Printf 在 MRE 中使用是个坏主意,我实际上想到的是这样的代码:

struct my_struct {
    int my_array[CCC]
    ... other stuff ...
}

问题是 my_array 有多大,所以我可以用另一种语言制作结构(python 通过 ctypes)并知道我需要多少 space。我知道对于结构我可以使用 pahole 但我希望只使用 gcc 并且在更一般的情况下(比如不在结构中的全局数组)。

#include <stdio.h>

#define AAA 1
#define BBB 2
#define CCC (AAA+BBB)

#define STRINGIFY(x) #x
#define PASTE(x) STRINGIFY(x)


int main(void)
{
  printf("CCC = '%s'\n", PASTE(CCC));
}

打印

CCC = '(1+10)'

打印相同的替代版本:

#include <stdio.h>

#define AAA 1
#define BBB 2
#define CCC (AAA+BBB)

#define STRINGIFY(x) #x
#define INTERMEDIATE(x) #x " = '" STRINGIFY(x) "'"

int main(void)
{
  printf("%s\n", INTERMEDIATE(CCC));
}

预处理器永远不会创建

#define CCC (1+10)

CCC的展开总是(AAA+BBB);只是宏展开的结果被重新扫描,以便有更多的宏展开,此时AAABBB分别变成了110

也许更清楚的例子是

#define AAA 1
#define CCC AAA
#define AAA "hello"

size_t x = sizeof CCC;

此代码将扩展为 "hello",而不是 1CCC 始终具有 AAA 的值;只是当 size_t x = sizeof CCC; 被处理时, AAA 本身将变成 "hello".

这个例子也证明了宏可以被重新定义,所以 "what is the value of CCC?" 甚至可能没有一个答案。

这就是为什么没有简单的编译器调用或切换的原因;你想要的根本不存在。

就是说,如果您可以使用自定义代码,您可以 运行 例如

#define AAA 1
#define BBB 10
#define CCC (AAA+BBB)
CCC

gcc -P -E 结果将是 (1+10).