1、 __attribute__ ((packed))的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,是GCC特有的语法。
2、 __attribute__ ((aligned(n)))的作用就是告诉编译器在编译过程中按照n字节对齐。常常用来在结构体后面进行修饰。
下面通过一段代码来进行测试
- #include <stdio.h>
- /*编译器默认是4字节对齐*/
- struct test{
- char a;
- int b;
- };
- /*按实际占用的空间大小*/
- struct test1{
- char a;
- int b;
- }__attribute__((packed));
- /*结构体大小必须4字节对齐*/
- struct test2{
- char a;
- int b;
- }__attribute__((aligned(4)));
- /*结构体大小必须8字节对齐*/
- struct test3{
- char a;
- int b;
- }__attribute__((aligned(8)));
- /*结构体大小必须16字节对齐*/
- struct test4{
- char a;
- int b;
- }__attribute__((aligned(16)));
- /*int 类型数据大小必须8字节对齐*/
- struct test5{
- char a;