前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C语言之——__attribute__

C语言之——__attribute__

作者头像
用户4645519
发布2020-09-07 11:04:57
1.1K0
发布2020-09-07 11:04:57
举报
文章被收录于专栏:嵌入式学习嵌入式学习

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

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

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

代码语言:javascript
复制
#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;
}
代码语言:javascript
复制
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
请按任意键继续. . .
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-08-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档