C语言之——__attribute__

__attribute__ ((packed)) 的作用就是告诉编译器取消结构在编译过程中的优化对齐,按照实际占用字节数进行对齐,是GCC特有的语法。这个功能是跟操作系统没关系,跟编译器有关 。

 __attribute__((aligned(4)));设置4字节对齐方式,和#pragma pack(4) 效果一样

可以参考:https://blog.csdn.net/zhangxiong2532/article/details/50826917

#include <stdio.h>

struct mystruct11 
{
    int a;
    char b;
    short c;
}__attribute__((packed));

struct mystruct21 
{
    char a;
    int b;
    short c;
}__attribute__((packed));

struct p  
{  
    int a;  
    char b;  
    char c;  
}__attribute__((aligned(4))) p1;



struct q  
{  
    int a;  
    char b;  
    struct p qn;  
    char c;  
}__attribute__((aligned(8))) q2;

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
    */
    
    printf("sizeof(int):%d, sizeof(char)=%d\n", sizeof(int), sizeof(char));
    printf("sizeof(p1):%d\n", sizeof(p1));

    printf("sizeof(q2):%d\n", sizeof(q2));
    
    return 0;
}
sizeof(struct mystruct11) = 8.
sizeof(struct mystruct21) = 10.
sizeof(int):4, sizeof(char)=1
sizeof(p1):8
sizeof(q2):24

--------------------------------
Process exited after 0.01857 seconds with return value 0
请按任意键继续. . .

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值