GNU GCC 编译器 - 对齐属性

GNU GCC compiler - aligned attribute

我正确地收到对齐警告

cast increases required alignment of target type [-Wcast-align]

由于以下代码而来自 GCC 编译器:

uint8_t array[100];

uint32_t foo;
foo = * ( (uint32_t *) &array[10]);

然后我使用 aligned 属性找出问题所在:

uint8_t array[100] __attribute__ ((aligned(4)));

uint32_t foo;
foo = * ( (uint32_t *) &array[10]);

尽管有这个技巧,我还是收到了同样的警告。这是正常现象还是警告应该消失?

想一想:&array[10] 即使与 __attribute__ ((aligned(4))) 也不会是 4 字节对齐的,因为您正在查看 4 字节对齐数组中的 10 字节偏移量。所以在这个例子中你只会得到 2 字节对齐,gcc 发出警告是正确的。尝试使用索引 12 而不是 10,警告 可能 消失。

__attribute__ ((aligned(4))) 仅对齐数组的 开头 ,而不是数组的每个元素。

如果开头对齐且偏移量为 10 且不能被 4 整除,则结果地址将不会对齐。