C++ GCC中的结构对齐(是否应在typedef中指定对齐?)

C++ GCC中的结构对齐(是否应在typedef中指定对齐?),c++,gcc,alignment,C++,Gcc,Alignment,很抱歉提出了一个愚蠢的问题,但是如果我需要确保结构/类/联合的对齐,我是否应该在typedef声明中添加属性((对齐(对齐)) class myAlignedStruct{} __attribute__ ((aligned(16))); typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not? 我应该在typedef声明中添加属性((对齐(对齐)) clas

很抱歉提出了一个愚蠢的问题,但是如果我需要确保结构/类/联合的对齐,我是否应该在typedef声明中添加属性((对齐(对齐))

class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?
我应该在typedef声明中添加属性((对齐(对齐))

class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?
不。。。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';
}
被接受的答案(“否”)是正确的,但我想澄清其中一个可能误导的部分。我想添加一条注释,但需要格式化一些代码;这就是新的答案

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';
}
这是不正确的,至少对GCC(OP的编译器)和GHS是这样。例如,下面的编译没有错误,表明对齐可以附加到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);
}

有点困惑,你是说是的,myAlignedStruct2应该对齐16个字节吗?@Als:我的意思是“我应该在typedef声明中添加属性((对齐(对齐))”:否。是的,“myAlignedStruct2[将]对齐16个字节”。上面添加了说明性代码和输出…My+1。没错。有两个问题&每个问题都明确提到是和否,这让问题变得非常清楚了。:)@Als:我现在和你在一起-我没有真正阅读代码注释。。。8-),只注意到一个问题。。。很抱歉绝对不是一个愚蠢的问题。我认为myAlignedStruct2的对齐方式与myAlignedStruct相同,但我想确定一下。您是否尝试过printf(“大小:%d,%d”,大小(myAlignedStruct),大小(myAlignedStruct2))@Shlublu:
sizeof
检查包装,但对齐方式不同!没有标准运算符,但GCC提供了
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu!这让你的问题更加有趣!这种情况的真实例子如下: