现在的位置: 首页 > 综合 > 正文

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

2013年10月26日 ⁄ 综合 ⁄ 共 1287字 ⁄ 字号 评论关闭

      此属性可以强制修改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字节对齐的问题,但是这样 我们得严格注意结构体对齐的问题。

抱歉!评论已关闭.