C 编程 #define struct { } 声明

c programming #define struct { } declaring

我在看 Glibc 代码。 glibc 队列的一些代码引起了我的注意。我无法为这个结构定义赋予意义。该结构没有名称。为什么?它是如何工作的?

#define LIST_ENTRY(type)                        \
struct {                                \
    struct type *le_next;   /* next element */          \
    struct type **le_prev;  /* address of previous next element */  \
}

Source

这实际上是一个预处理器宏,可以在其他地方扩展(很可能带有尾随名称)。

在该头文件开头的注释中有对 queue(3) man page 的引用,其中包含有关该宏和其他宏的更多详细信息:

The macro LIST_ENTRY declares a structure that connects the elements in the list.

以及使用示例:

LIST_HEAD(listhead, entry) head = LIST_HEAD_INITIALIZER(head);  
struct listhead *headp;                 /* List head. */
struct entry {  
  ...  
  LIST_ENTRY(entry) entries;      /* List. */  
  ...  
}  
*n1, *n2, *n3, *np, *np_temp;  

LIST_INIT(&head);                       /* Initialize the list. */  

n1 = malloc(sizeof(struct entry));      /* Insert at the head. */   
LIST_INSERT_HEAD(&head, n1, entries);

作为此 C 代码(不是 C++),并且 C 缺少模板,此预处理器宏可用于 "simulate" 模板(注意 type 参数)。

这是一个用于声明结构类型的宏,其中 nextprev 指针指向第二个结构类型的实例。第二种类型可以是父类型,因此您可以像这样创建 "linkable struct":

struct foo {
  LIST_ENTRY(foo) list;
  int value;
};

这将创建一个 struct foo,其中包含一个名为 list 的成员,该成员又是问题中的结构,指针指向 struct foo

我们现在可以创建一个 struct foo 的小链表,如下所示:

struct foo fa, fb;
fa.value = 47;
fa.list.le_next = &fb;
fa.list.le_prev = NULL;
fb.value = 11;
fb.list.le_next = NULL;
fb.list.le_prev = &fa.list.le_next;

我不是 100% 确定最后一行,但我认为它有点道理。