1.1 第一个宏定义
1.1.1 offset宏
#ifndef offsetof
#define offsetof(TYPE, MEMBER) ((size_t)&((TYPE*)0)->MEMBER) // 注意取地址符&
#endif
& 是对Member取地址的
1.1.2 编译器做了什么
offsetof 用于计算TYPE 结构体中MEMBER成员的偏移位置
- 那么问题来了, 直接使用0地址不会导致程序崩溃吗?
1.1.3
- 编译器清楚的指针结构体成员变量的偏移位置
- 通过结构图变了首地址与偏移量定位成员变量
1.2第二个宏定义
1.2.1 ( { }) 是啥
- ({}) 是GNU C编译器的语法扩展
- ({}) 类似于逗号表达式,结果为最后一个语句的值
void mathod_1()
{
int a = 0;
int b = 0;
int r = (a =1, b =2,a + b
);
printf("mathod_1 r = %d\n", r);
}
void mathod_2()
{
int r = ({
int a = 10;
int b = 20;
a + b;
});
printf("mathod_2 r = %d\n", r);
}
1.2.2 typeof 是一个关键字吗
- typeof 是GNU C编译器的特有关键字
- typeof 只在编译器生效,用于得到变量的类型
int main()
{
int i = 100;
typeof(i) j = i; // int j =i;
const typeof(i)* p =&j; // const int * p = &j;
printf("sizeof(j) = %d\n", sizeof(j));
printf("j =%d \n", j);
printf("p = %d\n", p);
return 0;
}
1.2.3 最后的原理
1.2.4 container_of 这个宏
- 报错
- 下面的程序看着没有错啊,看了半天才知道是没有加 “\”
- 正确形式
#ifndef container_of
#define container_of(ptr, type, member)({ \
const typeof(((type*)0)->member)* __mptr = (ptr); \
(type*)((char*)__mptr - offsetof(type, member)); \
})
#endif
- // 这行代码的意义 const typeof(((type*)0)->member)* __mptr = (ptr);
- // 这行代码是为了多一步类型检查
- 注意 container_of 这个宏只能在GNU编译器中使用,不能在 window 编译器中使用,要想使用,可以使用改写的版本
#ifndef container_of_new
#define container_of_new(ptr, type, member)((type*)((char*)(ptr) - offsetof(type, member)))
#endif
1.3 linux 内核链表剖析
1.3.1 目标
- 移植Linux内核链表, 使其适用于GNU编译器
- 分析Linux内核中链表的基本实现
1.3.2移植时的注意事项
- 清除文件间的依赖
- 清除平台相关代码(GNU C)
- ({ })
- typeof
- _builtin_prefetch
- static inline 在标准C中不能同时出现
1.3.3 Linux内核链表的实现
- 带有头节点的双向循环链表,且头结点为表中成员
- 头结点的next指针指向首节点
- 头结点的prev指针指向尾节点
1.3.4 Linux内核链表的结点定义
struct list_head {
struct list_head *next, *prev;
};
- Linux 内核链表的创建以及初始化
struct Node
{
struct list_head head;
int value;
}
int main(void)
{
struct Node l ={0};
struct list_head* list = (struct list_head*) &l;
INIT_LIST_HEAD(list);
}
参考一 : 狄泰软件课程
如有侵权:请联系邮箱 1986005934@qq.com