__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;
}

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

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值