Linux内核学习中---有关#define LIST_HEAD_INIT(name) { &(name), &(name) }的问题

最近在接触内核方面的东西,遇见如下一段代码:

struct list_head {
        struct list_head *next, *prev;        //双向链表
};

#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)



在网上看了很多前人工作,在这里自己做下总结。

 

来看数据结构体:

struct list_head {         struct list_head *next, *prev; }; 
//宏定义如下:
#define LIST_HEAD_INIT(name) { &(name), &(name) } 
#define LIST_HEAD(name) struct list_head name = LIST_HEAD_INIT(name) 


举例如下:

struct list_head foo = { &(foo) , &(foo)}

相当于:

struct list_head foo; foo.next = &foo; foo.prev = &foo;

另一个例子:

struct list_head test = LIST_HEAD (check); LIST_HEAD (check);

在C语言中我们使用的结构体对应实例:例如:

struct student{long int num;

char name[20];char sex;

char addr[20];

}a={10101,"Li yong tian",'M',“513477736”};

 

a的初始化是四项,与结构体的成员是一一对应的。而结构体中:

struct list_head foo = { &(foo) , &(foo)}

在本文中等价与

:struct list_head {        struct list_head *next, *prev; } foo = { &(foo) , &(foo)};

按照成员的对应赋值就是:

struct list_head foo; foo.next = &foo; foo.prev = &foo;

 

//如果我有一个定义了一个对象:
struct list_head mylist;
 
//then

LIST_HEAD(mylist);
==
struct list_head mylist = { &(mylist), &(mylist) } ;


总而言之:用同一个对象初始化next 和 prev

 

而对于最后一段代码:

 

#define INIT_LIST_HEAD(ptr) do { \
        (ptr)->next = (ptr); (ptr)->prev = (ptr); \
} while (0)


 

初始化就是把指针指向自己。在不同版本的源码中,这些函数的实现方式略有不同,例如在linux-2.6.26中,此函数不是宏定义,而是一个内联函数,不过它们所做的工作都是大同小异的,这一点在本文其他部分都一样,下面就不再提醒了。







   

你可能感兴趣的:(Linux内核学习中---有关#define LIST_HEAD_INIT(name) { &(name), &(name) }的问题)