我第一次尝试同时使用 X 宏和预处理器连接。
我已经阅读了很多关于 SO 与预处理器串联相关的其他问题,但我还无法理解它们或如何使这些问题适应我的用例。
项目列表是一堆 的 ID 号列表structs
,如下所示:
#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
?