linux内核修炼之道
目录
1. 宏定义类型表达式
#define min(x, y) ({\
typeof(x) _x=x;\
typeof(y) _y=y;\
(void)(&_x==&_y);\
_x>_y _y:_x;})
2. 零长度数组
struct usb_interface_cache {
unsigned num_altsetting;
...
struct usb_host_interface altsetting[0]; //零长度数组
};
结构的最后一个元素是零长度数组,它并不占用结构的空间,但它意味着这个结构体充满了变数,创建该结构体对象时,可以根据实际的需要指定这个可变长数组的空间;
3. 可变参数宏
#define debug(format, ...) fprintf(stderr, format, __VA_ARGS__)
其中“...”是可变参数,实际使用时它会替代__VA_ARGS__宏参数
#define debug(format, args...) fprintf(stderr, format, ##args)
通过参数的形式,让可变参数可读性更强,另外##表示参数args为NULL的时,##可以过滤掉前面的逗号
4. 标号元素
指定索引或结构体域名,可以调整顺序初始化
struct {
...
.read = generic_file_llseek;
...
}
5.特殊属性(__attribute__)
5.1 noreturn
5.2 format(archtype, string-index, first-to-check)
5.3 unused
5.4 section("section-name")
用于函数或变量,通常编译器将函数放在.text节,变量放在如.data或.bss,使用section属性可以让编译器将函数或变量指定放在指定的位置,这是linux特有的一种方式,如
#define __init __attribute__((__section__("__init.text")))__cold
#define __initdata __attribute__((__section__("__init.data")))__cold
#define __exitdata __attribute__((__section__("__init.data")))__cold
6. aligned(ALIGNMENT)
字节对齐,用于变量、结构体、或联合体,以字节为单位
7. packed
用于变量、结构体、或联合体成员时使用最小的字节对齐,用于变量、结构体、或联合体成员时使用最小的内存