GCC中的结构对齐(应该在typedef中指定对齐吗?)

Structure alignment in GCC (should alignment be specified in typedef?)

本文关键字:对齐 typedef 结构 GCC      更新时间:2023-10-16

对不起,这是一个愚蠢的问题,但如果我需要确保结构/类/联合的对齐,我应该添加属性((aligned(align)))到typedef声明吗?

class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?

我应该添加属性((aligned(align)))到typedef声明吗?

不…类型定义只是指定的实际类型的假名或别名,它们不作为单独的类型存在以具有不同的对齐方式,包装等。

#include <iostream>
struct Default_Alignment
{
    char c;
};
struct Align16
{
    char c;
} __attribute__ ((aligned(16)));
typedef Align16 Also_Align16;
int main()
{
    std::cout << __alignof__(Default_Alignment) << 'n';
    std::cout << __alignof__(Align16) << 'n';
    std::cout << __alignof__(Also_Align16) << 'n';
}
输出:

1
16
16

公认的答案("否")是正确的,但我想澄清其中一个可能令人误解的部分。我会添加注释,但需要格式化一些代码;因此有了新的答案。

类型定义只是指定的实际类型的假名或别名,它们不作为单独的类型存在以具有不同的对齐方式,包装等。

这是不正确的,至少对于GCC (OP的编译器)和li。例如,下面的编译没有错误,表明可以将对齐附加到typedef。

反常对齐(大于对象的大小)仅仅是为了震慑和娱乐价值。

#define CASSERT( expr ) { typedef char cassert_type[(expr) ? 1 : -1]; }
typedef __attribute__((aligned(64))) uint8_t aligned_uint8_t;
typedef struct
{
    aligned_uint8_t t;
} contains_aligned_char_t;
void check_aligned_char_semantics()
{
    CASSERT(__alignof(aligned_uint8_t) == 64);
    CASSERT(sizeof(aligned_uint8_t) == 1);
    CASSERT(sizeof(contains_aligned_char_t) == 64);
}