字节对齐---arm-linux-gcc和gcc

来源:互联网 发布:java web 日志框架 编辑:程序博客网 时间:2024/06/09 16:33

下面是从别处找来的,很久前看到

linux下GCC 对齐方式的最大模数是4,即使设置为8,那也只是4字节对齐。

下面内容原地址:

http://blog.sina.com.cn/s/blog_4c451e0e0100gx3o.html

方法一:
#include <stdio.h>
#pragma pack(1)
struct abc
{
    double a;
    int    b;
    char   c;
};
#pragma pack()

void main()
{
    printf( "sizeof( struct abc ) = %d/n", sizeof( struct abc ) );
}

以上代码
gcc tBytePadding.c -o tBytePadding
Ubuntu执行结果:sizeof( struct abc ) = 13

/usr/local/arm/2.95.3/bin/arm-linux-gcc -I /usr/local/arm/2.95.3/arm-linux/include tBytePadding.c -o tBytePadding
执行结果:sizeof( struct abc ) = 16 <-- 依然四字对齐了,没有一字节对齐
方法二:
#include <stdio.h>

typedef struct tagabc
{
    double a;
    int    b;
    char   c;
}__attribute__( ( packed, aligned( 1 ) ) ) abc;

void main()
{
    printf( "sizeof( abc ) = %d/n", sizeof( abc ) );
}


#include <stdio.h>
struct abc
{
    double a;
    int    b;
    char   c;
}__attribute__( ( packed, aligned(1) ) );

void main()
{
    printf( "sizeof( struct abc ) = %d/n", sizeof( struct abc ) );
}

以上代码
gcc tBytePadding.c -o tBytePadding
Ubuntu执行结果:sizeof( struct abc ) = 13

/usr/local/arm/2.95.3/bin/arm-linux-gcc -I /usr/local/arm/2.95.3/arm-linux/include tBytePadding.c -o tBytePadding
执行结果:sizeof( struct abc ) = 13
推荐使用方法二的第一种!
注意:
typedef struct tagabc
{
    double a;
    int    b;
    char   c;
}__attribute__( ( packed, aligned( 1 ) ) );

tagabc abc;

以上写法会报此错误:warning: ‘packed’ attribute ignored

typedef struct tagabc
{
    double a;
    int    b;
    char   c;
} abc __attribute__( ( packed, aligned( 1 ) ) );

以上写法也会报此错误:warning: ‘packed’ attribute ignored

 

原创粉丝点击