[英]c programming #define struct { } declaring
I was looking at Glibc codes. 我在看Glibc代码。 Some codes of glibc's queue caught my attention.
一些glibc队列的代码引起了我的注意。 I couldn't give a meaning to this struct definition.
我无法给出这个结构定义的含义。 This struct doesn't have a name.
此结构没有名称。 Why?
为什么? How does it work?
它是如何工作的?
#define LIST_ENTRY(type) \
struct { \
struct type *le_next; /* next element */ \
struct type **le_prev; /* address of previous next element */ \
}
That is actually a preprocessor macro, that could be expanded (most probably with trailing name) somewhere else. 这实际上是一个预处理器宏,可以在其他地方扩展(最有可能是尾随名称)。
In the comments at the start of that header file there is a reference to queue(3) man page that contains more details on that and other macros: 在该头文件开头的注释中,有一个对queue(3)手册页的引用,其中包含有关该头文件和其他宏的更多详细信息:
The macro LIST_ENTRY declares a structure that connects the elements in the list.
宏LIST_ENTRY声明了一个连接列表中元素的结构。
And an example of use: 以及使用示例:
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);
Being this C code (not C++), and C lacks templates, this preprocessor macro can be used to "simulate" templates (note the type
parameter). 作为这个C代码(不是C ++),而C缺少模板,这个预处理器宏可以用来“模拟”模板(注意
type
参数)。
It's a macro that is used to declare a struct type, with next
and prev
pointers to instances of a second struct type. 它是一个用于声明结构类型的宏,带有指向第二个结构类型实例的
next
和prev
指针。 That second type can be a parent type, so you can make a "linkable struct" like this: 第二种类型可以是父类型,因此您可以创建一个“可链接的结构”,如下所示:
struct foo {
LIST_ENTRY(foo) list;
int value;
};
This creates a struct foo
containing a member called list
which in turn is the structure in the question, with the pointers pointing at struct foo
. 这将创建一个包含名为
list
的成员的struct foo
,而该成员又是问题中的结构,指针指向struct foo
。
We can now create a little linked list of struct foo
s like so: 我们现在可以像这样创建一个
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;
I'm not 100% sure about the last line, but I think it kind of makes sense. 我对最后一行并不是100%肯定,但我认为这有点道理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.