GCC推荐的对齐指令:_attribute_((packed))和_attribute_((aligned(n)))

来源:互联网 发布:vmware mac 使用教程 编辑:程序博客网 时间:2024/05/19 04:03

1、使用方法
使用attribute((packed))和attribute((aligned(n)))时,直接放在类型定义的后面,那么该类型就以指定的方式进行对齐。packed的作用是取消对齐,aligned(n)表示对齐方式。
2、attribute((packed))使用实例

#include <stdio.h>struct mystruct11 {    int a;    char b;    short c;}_attribute_((packed));struct mystruct21 {    char a;    int b;    short c;}_attribute_((packed));int main(void){    printf("sizeof(struct mystruct11) = %d.\n",sizeof(struct mystruct11));    printf("sizeof(struct mystruct21) = %d.\n",sizeof(struct mystruct21));    /*    两个不同结构体1字节对齐的结构    struct mystruct11                         struct mystruct21    1字节对齐                          1字节对齐    4                                                   1    1                                                   4    2                                                   2    */    return 0;}
原创粉丝点击