__attribute__
__attribute__
1.__attribute__ ((attribute-list))
__attribute__关键字主要是用来在函数或数据声明中设置其属性。
给函数赋给属性的主要目的在于让编译器进行优化。
例如:函数声明中的__attribute__((noreturn)),就是告诉编译器这个函数不会返回给调用者,以便编译器在优化时去掉不必要的函数返回代码。
2. __attribute__ ((packed))
让编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,这样子两边都需要使用 __attribute__ ((packed))取消优化对齐,就不会出现对齐的错位现象。
#include <stdio.h> typedef struct TEST { char a; int b; } test; int main(void) { printf("sizeof()=%d.\n",sizeof(test)); return 0; }
输出结果是:8
#include <stdio.h> typedef struct TEST { char a; int b; }__attribute__((packed)) test; int main(void) { printf("sizeof()=%d.\n",sizeof(test)); return 0; }
输出结果:5
青青园中葵,朝露待日晞。
阳春布德泽,万物生光辉。
常恐秋节至,焜黄华叶衰。
百川东到海,何时复西归?
少壮不努力,老大徒伤悲!