抱歉有一个愚蠢的问题,但如果我需要确保结构/类/联合的对齐,我应该将属性((aligned(align))添加到typedef声明吗?
class myAlignedStruct{} __attribute__ ((aligned(16)));
typedef myAlignedStruct myAlignedStruct2; // Will myAlignedStruct2 be aligned by 16 bytes or not?
Run Code Online (Sandbox Code Playgroud)
Ton*_*roy 10
我应该在typedef声明中添加属性((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';
}
Run Code Online (Sandbox Code Playgroud)
输出:
1
16
16
Run Code Online (Sandbox Code Playgroud)
接受的答案("否")是正确的,但我想澄清一个可能具有误导性的部分.我要添加注释,但需要格式化一些代码; 因此,新的答案.
类型定义只是假名或指定的实际类型别名,它们不存在,作为一个独立的类型有不同的定位,包装等.
这是不正确的,至少对于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);
}
Run Code Online (Sandbox Code Playgroud)