通过设置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

猜你喜欢

转载自lobin.iteye.com/blog/2364160