32 位处理器字的默认结构对齐

Default structure alignment for 32 bit processor word

我正在使用为 32 位 ARM 处理器编译的结构。

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

如果我什么都不用,__attribute__ ((aligned (8)))__attribute__ ((aligned (4))) 我在结构大小和元素偏移方面得到相同的结果。总大小为 24。所以我认为它始终对齐 8(偏移量适用于 a=0b=2c=8d=16e=20)。

为什么 8 是编译器选择的默认对齐方式?不应该是 4 因为是 32 字处理器吗?

在此先感谢伙伴们。

aligned 属性仅指定最小对齐方式,而不是精确对齐方式。来自 gcc documentation:

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

在您的平台上 double 的自然对齐方式是 8,所以这就是使用的方式。

因此,要获得您想要的内容,您需要组合 alignedpacked 属性。使用以下代码,c 的偏移量为 4(使用 offsetof 测试)。

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