通过设置GCC编译参数-fpack-struct[=N]指定内存对齐

通过设置GCC编译参数-fpack-struct[=N]指定内存对齐

 

举个例子:

#include <stdio.h>

#include <stdlib.h>

#include <stddef.h>

 

struct test_s {

    int i;

    char c;

    double d;

    char a[];

};

 

#

#

#

#

 

int main(int argc, char **argv)

{

    printf("sizeof(struct test_s)=%d\n", sizeof(struct test_s));

 

    printf("offsetof(struct test_s, i)=%d, offsetof(struct test_s, c)=%d, offsetof(struct test_s, d)=%d, offsetof(struct test_s, a)=%d\n",

        offsetof(struct test_s, i),

        offsetof(struct test_s, c),

        offsetof(struct test_s, d),

        offsetof(struct test_s, a));

    return 0;

}

 

 

 

gcc -fpack-struct=4 -c offsetof_test.c  -o offsetof_test.o

gcc offsetof_test.o  -o offsetof_test

 

./offsetof_test 

sizeof(struct test_s)=16

offsetof(struct test_s, i)=0, offsetof(struct test_s, c)=4, offsetof(struct test_s, d)=8, offsetof(struct test_s, a)=16

 

 

 

 

 

gcc -fpack-struct=2 -c offsetof_test.c  -o offsetof_test.o

gcc offsetof_test.o  -o offsetof_test

 

./offsetof_test 

sizeof(struct test_s)=14

offsetof(struct test_s, i)=0, offsetof(struct test_s, c)=4, offsetof(struct test_s, d)=6, offsetof(struct test_s, a)=14

 

 

 

 

 

 

gcc -fpack-struct -c offsetof_test.c  -o offsetof_test.o

gcc offsetof_test.o  -o offsetof_test

 

./offsetof_test 

sizeof(struct test_s)=13

offsetof(struct test_s, i)=0, offsetof(struct test_s, c)=4, offsetof(struct test_s, d)=5, offsetof(struct test_s, a)=13

 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值