【发布时间】:2017-09-08 11:05:12
【问题描述】:
我正在尝试应用X Macro 概念,以便有可能将所有结构成员初始化为自定义默认(无效)值。我写了以下代码:
#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) 调用替换为 -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 could refer to other macros。你知道为什么替换失败吗?有什么解决办法吗?
我可以接受foo_invalidate,但我不愿意放弃在初始化时直接使用值的一步。
【问题讨论】:
-
您将
X(name)定义为-1,周围的#define为foo_DEFAULT_VALUE,但不是您实际使用它的位置。您需要在static struct foo test = foo_DEFAULT_VALUE;行周围定义发生替换的X宏。
标签: c macros initialization c-preprocessor