为什么这个嵌套的宏替换失败了?

我正在尝试应用X宏概念,以便有可能将所有struct成员初始化为自定义默认(无效)值。 我写下面的代码:

#define LIST_OF_STRUCT_MEMBERS_foo \ X(a) \ X(b) \ X(c) #define X(name) int name; struct foo { LIST_OF_STRUCT_MEMBERS_foo }; #undef X #define X(name) -1, static inline void foo_invalidate(struct foo* in) { *in = (struct foo){ LIST_OF_STRUCT_MEMBERS_foo }; } #undef X #define X(name) -1, #define foo_DEFAULT_VALUE { LIST_OF_STRUCT_MEMBERS_foo } #undef X static struct foo test = foo_DEFAULT_VALUE; 

但是,当我运行预处理器时, foo_DEFAULT_VALUE的定义无法用X(name)替换X(name)调用-1,

预处理器输出:

 struct foo { int a; int b; int c; }; static inline void foo_invalidate(struct foo* in) { *in = (struct foo){ -1, -1, -1, /*Here the substitution worked nicely*/ }; } static struct foo test = { X(a) X(b) X(c) }; /*Why this substitution failed?*/ 

我以为C-macros可以引用其他宏 。 你知道为什么替换失败了吗? 有没有解决方法?

我可以使用foo_invalidate ,但是我不愿意放弃在初始化时直接使用值的一步。

让我们假装我们是预处理器并遇到这条线:

 static struct foo test = foo_DEFAULT_VALUE; 

通过1:

 static struct foo test = { LIST_OF_STRUCT_MEMBERS_foo }; 

通过2:

 static struct foo test = { X(a) X(b) X(c) }; 

传递3:由于此线上未定义X因此无法展开。


一种解决方法可能是定义一个const变量(可能但不一定是static )用作默认值:

 #define X(name) -1, static const struct foo foo_DEFAULT_VALUE = { LIST_OF_STRUCT_MEMBERS_foo }; #undef X 

哪个产生:

 static const struct foo foo_DEFAULT_VALUE = { -1, -1, -1, }; 

您可能喜欢免费版的X_Macros,
它减少了在每次使用时定义和取消定义所需的必要护理
并且更适合在多个代码文件中的头文件和用法中定义:

 #define LIST_OF_STRUCT_MEMBERS_foo(mode) \ X_##mode(a) \ X_##mode(b) \ X_##mode(c) #define X_struct(name) int name; #define X_list(name) -1, #define foo_DEFAULT_VALUE { LIST_OF_STRUCT_MEMBERS_foo(list) } struct foo { LIST_OF_STRUCT_MEMBERS_foo(struct) }; static inline void foo_invalidate(struct foo* in) { *in = (struct foo){ LIST_OF_STRUCT_MEMBERS_foo(list) }; } static struct foo test = foo_DEFAULT_VALUE; 

输出(gcc -E):

 struct foo { int a; int b; int c; }; static inline void foo_invalidate(struct foo* in) { *in = (struct foo){ -1, -1, -1, }; } static struct foo test = { -1, -1, -1, }; 

您也可以尝试检查扩展宏的输出。 如果您使用gcc作为编译器, gcc -E >> full_src.txt'将有所帮助。 更多细节在这里: 查看扩展的C宏