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

1、 __attribute__ ((packed))的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,是GCC特有的语法。
2、 __attribute__ ((aligned(n)))的作用就是告诉编译器在编译过程中按照n字节对齐。常常用来在结构体后面进行修饰。

下面通过一段代码来进行测试

  1. #include <stdio.h>
  2.  
  3. /*编译器默认是4字节对齐*/
  4. struct test{
  5.     char a;
  6.     int b;
  7. };
  8.  
  9. /*按实际占用的空间大小*/
  10. struct test1{
  11.     char a;
  12.     int b;
  13. }__attribute__((packed));
  14.  
  15. /*结构体大小必须4字节对齐*/
  16. struct test2{
  17.     char a;
  18.     int b;
  19. }__attribute__((aligned(4)));
  20.  
  21. /*结构体大小必须8字节对齐*/
  22. struct test3{
  23.     char a;
  24.     int b;
  25. }__attribute__((aligned(8)));
  26.  
  27. /*结构体大小必须16字节对齐*/
  28. struct test4{
  29.     char a;
  30.     int b;
  31. }__attribute__((aligned(16)));
  32.  
  33. /*int 类型数据大小必须8字节对齐*/
  34. struct test5{
  35.     char a;
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值