SunStudio C++编译器中的对齐

Alignment in SunStudio C++ compiler

本文关键字:对齐 编译器 C++ SunStudio      更新时间:2023-10-16

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

在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"不适用,因为它只适用于全局或静态变量,并且它需要变量名。

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

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

不幸的是,C++中不支持此属性(至少通过Sun C++5.10)。

至少值得一试:

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

当然,这会让访问变得更加痛苦,并扼杀直接赋值,因此可能会破坏整个代码库。此外,它完全基于这样一种假设,即包括一个更大的类型,由于其大小,被假设具有32位的"本机对齐",使得union作为一个整体在32位上对齐。

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

自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