Recently, I encountered the following code in terms of kernel exposure:
Struct list_head {struct list_head * Next, * Prev; // bidirectional linked list}; # define list_head_init (name) {& (name), & (name)} # define list_head (name) \ struct list_head name = list_head_init (name) # define init_list_head (PTR) do {\ (PTR)-> next = (PTR); (PTR)-> Prev = (PTR ); \} while (0)
I have read a lot of previous work on the Internet, and I will summarize it here.
Let's look at the data structure:
struct list_head { struct list_head *next, *prev; };
// Macro definition:
#define LIST_HEAD_INIT(name) { &(name), &(name) }
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name)
Example:
Struct list_head Foo = {& (FOO), & (FOO )}
Equivalent:
Struct list_head Foo; Foo. Next = & Foo; Foo. Prev = & Foo;
Another example:
Struct list_head test = list_head (check );
In the C language, we use the following struct instance: for example:
Struct student {long int num;
Char name [20]; char sex;
Char ADDR [20];
} A = {10101, "Li Yong Tian", 'M', "513477736 "};
The initialization of A is four items, which correspond to the members of the struct one by one. In the struct:
Struct list_head Foo = {& (FOO), & (FOO )}
Medium price and
: Struct list_head {struct list_head * Next, * Prev;} Foo = {& (FOO), & (FOO )};
Assign values based on the corresponding members:
Struct list_head Foo; Foo. Next = & Foo; Foo. Prev = & Foo;
// If I have an object defined: struct list_head mylist; // thenlist_head (mylist) ;== struct list_head mylist ={& (mylist), & (mylist )};
All in all: use the same object to initialize next and Prev
For the last piece of code:
#define INIT_LIST_HEAD(ptr) do { \ (ptr)->next = (ptr); (ptr)->prev = (ptr); \} while (0)
During initialization, the pointer is directed to itself. In different versions of the source code, the implementation of these functions is slightly different, for example, in the linux-2.6.26, this function is not a macro definition, but an inline function, but they do the same work, this is the same in all other parts of this article, so we will not remind you again below.