gcc __attribute__ ((packed)) || __attribute__ ((aligned(4))) 2

8 篇文章 0 订阅

      此属性可以强制修改gcc的对齐方式

      一般软件的2进制协议中,会定义一系列的规范,32位机一般会定义4字节对齐的协议,这样对于32位机来说速度是最快的。

      最近发现gcc一个问题,在一个结构体包含unsignd long long (64位)类型时会导致结构体8字节对齐,且__attribute__ ((aligned(4))) 

竟然无效

      本例子用的x86 编译器版本

#gcc --version
gcc (GCC) 4.1.3 20080704 (prerelease) (Debian 4.1.2-25)
Copyright (C) 2006 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

# arm-linux-gcc --version
arm-linux-gcc ((gcc4.4-290+uclibc_0.9.32.1+eabi+linuxpthread)) 4.4.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

      直接上例子程序

#include <stdio.h>

typedef unsigned long long ullong;
typedef struct  
{
    char    a;
    ullong  b;
    int     c;
/*} __attribute__ ((packed)) test ;*/
/*} __attribute__ ((aligned (4))) test ;*/
} test;

int main ( int argc, char *argv[] )
{
    printf("file:%s, line:%d, sizeof(test):%d\n", __FILE__, __LINE__, sizeof(test));
    return 0;
}
x86 32运行结果

file:test.c, line:15, sizeof(test):16
arm contex A9 运行结果

file:test.c, line:15, sizeof(test):24

结果说明在arm编译器成了8字节对齐 x86编译器还是4字节对齐

为了让该结构体4字节对齐,我们采用

__attribute__ ((aligned (4)))

强制对齐

输出结果还是

file:test.c, line:15, sizeof(test):24
无奈使用单字节对齐

__attribute__ ((aligned (4))) test
输出结果为

file:test.c, line:15, sizeof(test):13

这样虽然解决了我们4字节对齐的问题,但是这样 我们得严格注意结构体对齐的问题。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值