我试图围绕使用宏来定义数据结构操作的概念。以下代码是使用 FreeBSD 中内置列表库的简单示例。在库中,所有操作都定义为宏。我也在其他几个库中看到了这种方法。
我可以看到这有一些优点,例如。能够使用任何数据结构作为列表中的元素。但我不太明白这是如何工作的。例如:
- 是什么stailhead?这似乎是“刚刚”定义的。
- 如何传递head和传递entries给函数?
- 什么类型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;
};
所以我猜head是 type struct stailhead。
#include <stdio.h>
#include <stdlib.h>
#include <sys/queue.h>
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;i<10;i++){
                n1 = malloc(sizeof(struct stailq_entry));   /* Insert at the head. */
                n1->value = 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);
}