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

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

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值