__attribute__ ((packed)) 和 __attribute__ ((aligned(4)))的用法

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;
    int __attribute__((aligned(8))) b;
};


int main()
{
    printf("test:%d\n",sizeof(struct test));
    printf("test1:%d\n",sizeof(struct test1));
    printf("test2:%d\n",sizeof(struct test2));
    printf("test3:%d\n",sizeof(struct test3));
    printf("test4:%d\n",sizeof(struct test4));
    printf("test5:%d\n",sizeof(struct test5));

    return 0;
}

编译执行的结果:
在这里插入图片描述

转自:http://blog.chinaunix.net/uid-30271883-id-5679180.html