使用C中的宏来定义数据结构

我试图围绕使用宏来定义数据结构操作的概念。 以下代码是在FreeBSD中使用内置列表库的简单示例。 在库中,所有操作都定义为宏。 我也在其他几个库中看到了这种方法。

我可以看到这有一些优点,例如。 能够将任何数据结构用作列表中的元素。 但我不太明白这是如何工作的。 例如:

  1. 什么是stailhead ? 这似乎是“正义”的定义。
  2. 如何将headentries传递给函数?
  3. 什么类型的head ,我怎么能声明指向它的指针?

我可以使用这个技术的标准名称搜索谷歌,或任何解释这个概念的书吗? 关于这项技术如何运作的任何链接或良好解释将非常感激。

感谢Niklas B.我跑了gcc -E并得到了head这个定义

 struct stailhead { struct stailq_entry *stqh_first; struct stailq_entry **stqh_last; } head = { ((void *)0), &(head).stqh_first }; 

这对于stailq_entry

 struct stailq_entry { int value; struct { struct stailq_entry *stqe_next; } entries; }; 

所以我猜headstruct stailhead类型。

 #include  #include  #include  struct stailq_entry { int value; STAILQ_ENTRY(stailq_entry) entries; }; int main(void) { STAILQ_HEAD(stailhead, stailq_entry) head = STAILQ_HEAD_INITIALIZER(head); struct stailq_entry *n1; unsigned i; STAILQ_INIT(&head); /* Initialize the queue. */ for (i=0;ivalue = i; STAILQ_INSERT_HEAD(&head, n1, entries); } n1 = NULL; while (!STAILQ_EMPTY(&head)) { n1 = STAILQ_LAST(&head, stailq_entry, entries); STAILQ_REMOVE(&head, n1, stailq_entry, entries); printf ("n2: %d\n", n1->value); free(n1); } return (0); } 

首先阅读此内容以了解这些宏的作用。 然后转到queue.h 。 你会在那里得到宝藏!

我为你找了几个金币 –

 #define STAILQ_HEAD(name, type) \ struct name { \ struct type *stqh_first;/* first element */ \ struct type **stqh_last;/* addr of last next element */ \ } 

让我们深入挖掘并回答您的问题

什么是搁浅? 这似乎是“正义”的定义。

 #define STAILQ_HEAD(name, type) \ struct name { \ struct type *stqh_first;/* first element */ \ struct type **stqh_last;/* addr of last next element */ \ } STAILQ_HEAD(stailhead, entry) head = STAILQ_HEAD_INITIALIZER(head); struct stailhead *headp; /* Singly-linked tail queue head. */ 

所以stailhead是一个结构

如何将头和条目传递给函数?

 #define STAILQ_ENTRY(type) \ struct { \ struct type *stqe_next; /* next element */ \ } 

所以entrieshead (如前所述)只是结构,你可以在传递其他结构时传递它们。 &structure_variable

什么类型的头,我怎么能声明指向它的指针?

已经解释过了!

阅读此手册页,了解漂亮的例子。