我試圖應用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
定義失敗-1,
預處理器的輸出來替代X(name)
電話:
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
住在一起,但我不願放棄直接在初始化時使用的值。
你有''('name)'定義爲'-1,'''define''foo_DEFAULT_VALUE'',但不是你真正使用它的地方。你需要在'static struct foo test = foo_DEFAULT_VALUE'行的周圍定義'X'宏。 – Dmitri