简体   繁体   中英

Default structure alignment for 32 bit processor word

I'm working with an struct compiled for a 32bit ARM processor.

typedef struct structure {
   short a;
   char b;
   double c;
   int d;
   char e;
}structure_t;

If I use nothing, __attribute__ ((aligned (8))) or __attribute__ ((aligned (4))) I get the same results in terms of structure size and elements offset. Total size is 24. So I think it is always aligning to 8 (offsets are for both a=0 , b=2 , c=8 , d=16 , e=20 ).

Why is 8 the default alignment chosen by the compiler? Should not it be 4 because is a 32 word processor?

Thanks in advance mates.

The aligned attribute only specifies a minimum alignment, not an exact one. From gcc documentation :

The aligned attribute can only increase the alignment; but you can decrease it by specifying packed as well.

And the natural alignment of double is 8 on your platform, so that is what is used.

So to get what you want you need to combine the aligned and packed attributes. With the following code, c has offset 4 (tested using offsetof ).

typedef struct structure {
   short a;
   char b;
   __attribute__((aligned(4))) __attribute__((packed)) double c;
   int d;
   char e;
} structure_t;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM