1
我試圖在一起使用X宏和預處理器連接,兩者都是第一次。爲X宏連接多個標記
我已經閱讀了許多與預處理器級聯相關的其他問題,但還沒有能夠圍繞它們或者如何將它們適用於我的用例。
項目的列表是一堆structs
ID號的列表,像這樣:
#define LIST_OF_ID_NUMS \
X(1) \
X(2) \
X(3) \
X(4) \
X(5) \
X(6) \
X(7) \
X(8) \
X(9) \
X(10) \
X(11)
我可以聲明結構像這樣:
#define X(id_num) static myFooStruct foo_## id_num ;
LIST_OF_ID_NUMS
#undef X
// gives: 'struct myFooStruct foo_n;' where 'n' is an ID number
現在我也想初始化每個結構的一個成員等於ID號,例如foo_n.id = n;
。我已經能夠實現第一令牌串聯,通過以下:
#define X(id_num) foo_## id_num .id = 3 ;
LIST_OF_ID_NUMS
#undef X
// gives: 'foo_n.id = x' where 'x' is some constant (3 in this case)
但我一直無法理解如何正確地進一步擴大的想法,這樣所分配的值也被替換。我曾嘗試:
#define X(id_num) foo_## id_num .id = ## id_num ;
LIST_OF_ID_NUMS
#undef X
// Does NOT give: 'foo_n.id = n;' :(
及各種嘗試使用在雙間接的級聯。但一直沒有成功。造成錯誤的上述嘗試,如在LIST_OF_ID_NUMS
每個項目下面:
foo.c:47:40: error: pasting "=" and "1" does not give a valid preprocessing token
#define X(id_num) foo_## id_num .id = ## id_num ;
^
foo.c:10:5: note: in expansion of macro 'X'
X(1) \
^
foo.c:48:2: note: in expansion of macro 'LIST_OF_ID_NUMS '
LIST_OF_ID_NUMS
我怎樣才能最好的實現形式foo_n.id = n
?
哇,成功了!這意味着我的理解甚至比我想到的預處理器級聯更少:\ – Toby
@Toby您需要在此處使用標記粘貼來獲取'foo_42'(一個標記)而不是'foo_42'(兩個標記,稍後會出現語法錯誤) 。但'= 42''不一定是一個單一的標記(實際上不能是一個),所以在這裏沒有標記粘貼。 – Quentin
啊,光明!謝謝@Quentin – Toby