【问题标题】:Alignment in SunStudio C++ compilerSunStudio C++ 编译器中的对齐
【发布时间】:2012-01-24 09:43:29
【问题描述】:

我需要为 4 字节对齐的 2 字节变量声明类型别名。

在 GCC、XL C/C++ (AIX)、aCC (HP-UX) 中我可以使用以下代码:

typedef uint16_t AlignedType __attribute__ ((aligned (4)));

在 Windows 中我可以使用:

typedef __declspec(align(4)) unsigned __int16 AlignedType;

如何在 SunStudio C++ 11 中声明相同的类型?

“pragma align”不适合,因为它仅适用于全局或静态变量,并且需要变量名。

【问题讨论】:

  • 相关,您也可以使用__alignof__ 来确定SunCC 编译器的对齐方式。它是 GCC 的 __alignof__ 之类的扩展。它在 Solaris 9 上的 SunCC 5.8 测试良好。感谢OpenCSW 提供对他们的compile farm 的访问以测试旧的 x86 和 Sparc 机器。

标签: c++ c memory-alignment sunstudio


【解决方案1】:

从 Sun C 5.9 (Sun ONE Studio 12) 开始,支持对齐属性:

typedef uint16_t AlignedType __attribute__ ((aligned (4)));

很遗憾,C++ 不支持此属性(至少在 Sun C++ 5.10 中)。

【讨论】:

    【解决方案2】:

    至少值得一试:

    typedef union {
      uint16_t value;
      uint32_t _dummy;
    } AlignedType;
    

    这当然会使访问变得更加痛苦,并且会终止直接赋值,因此它可能会破坏您的整个代码库。此外,它纯粹是基于这样的假设,即包含一个更大的类型(由于具有该大小而被假定具有 32 位的“本机对齐”),使得 union 作为一个整体在 32 位上对齐。

    【讨论】:

    • 这行不通。变量必须对齐 4 个字节,但变量的大小必须是 2 个字节!例如 st1 的大小必须是 8 字节,而 st2 的大小必须是 12 字节。结构 st1 { uint32_t f1;对齐类型 f3; int16_t f2; };结构 st2 { uint32_t f1;对齐类型 f3;对齐类型 f2; };
    【解决方案3】:

    对于未来的参考,当编译器赶上时,C++11 具有标准对齐属性,请参阅alignasN3242 中的[dcl.align])。

    【讨论】:

      【解决方案4】:

      从 Sun C++ 5.12 SunOS_sparc 2011/11/16 开始,根据 DRH 的回复,C++ 似乎支持 gcc 语法:

      typedef uint16_t AlignedType8 __attribute__ ((aligned (8)));
      typedef uint16_t AlignedType4 __attribute__ ((aligned (4)));
      typedef uint16_t AlignedType2 __attribute__ ((aligned (2)));
      cout << __alignof__(AlignedType8) << ' ' << __alignof__(AlignedType4) << ' ' << __alignof__(AlignedType2) << endl;
      

      输出是:

      8 4 2

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-27
        • 2012-05-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多