【问题标题】:Structure alignment in GCC (should alignment be specified in typedef?)GCC 中的结构对齐(是否应该在 typedef 中指定对齐?)
【发布时间】:2011-10-10 19:08:32
【问题描述】:

抱歉问了一个愚蠢的问题,但是如果我需要确保结构/类/联合的对齐,我应该在 typedef 声明中添加 attribute((aligned(align))) 吗?

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

【问题讨论】:

  • 绝对不是一个愚蠢的问题。我认为 myAlignedStruct2 的对齐方式与 myAlignedStruct 相同,但希望确定这一点。你试过 printf("sizes: %d, %d", sizeof(myAlignedStruct), sizeof(myAlignedStruct2)); ?
  • @Shlublu: sizeof 检查包装,但对齐方式不同!没有标准运算符,但 GCC 提供了__alignof__(),如我的回答所示。
  • 啊,对不起,我搞错了!这让您的问题更加有趣!

标签: c++ gcc alignment


【解决方案1】:

我应该在 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';
}

输出:

1
16
16

【讨论】:

  • 有点迷茫,你的意思是对,myAlignedStruct2 是按16字节对齐的?
  • @Als:我的意思是“我应该在 typedef 声明中添加属性((对齐(对齐)))吗?”:不。是的,“myAlignedStruct2 [将] 对齐 16 个字节”。上面添加了说明性代码和输出....
  • 我的 +1。那是正确的。有两个 Q 并且每个问题都明确提到是和否,现在已经很清楚了。 :)
  • @Als:我现在和你在一起 - 我还没有真正阅读代码 cmets...8-),只注意到一个问题...对不起!
【解决方案2】:

接受的答案(“否”)是正确的,但我想澄清其中一个可能具有误导性的部分。我会添加评论,但需要格式化一些代码;因此有了新的答案。

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

这是不正确的,至少对于 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);
}

【讨论】:

猜你喜欢
  • 2011-02-02
  • 2012-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-15
  • 2011-06-05
  • 2018-02-24
相关资源
最近更新 更多