SunStudio C++编译器中的对齐方式

3

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


相关的是,您也可以使用__alignof__来确定SunCC编译器的对齐方式。这是类似于GCC的__alignof__的扩展。它在Solaris 9上的SunCC 5.8版本中测试良好。感谢OpenCSW提供访问他们的编译农场以测试旧的x86和Sparc机器。 - jww
4个回答

2
自Sun C 5.9版(Sun ONE Studio 12)起,支持使用aligned属性:
typedef uint16_t AlignedType __attribute__ ((aligned (4)));

很不幸,这个属性在C++中不被支持(至少在Sun C++ 5.10中是这样)。


1

这个值得至少尝试一下:

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

这当然使得访问有点痛苦,并且杀死了直接赋值,因此可能会破坏您的整个代码库。此外,它完全基于一种假设,即包含一个较大类型(由于其大小而被假定具有“本机对齐”32位),使得整个union对齐在32位上。


1
无法工作。变量必须按4字节对齐,但变量的大小必须为2字节!例如,st1的大小必须为8字节,但st2的大小必须为12字节。结构体st1 { uint32_t f1; AlignedType f3; int16_t f2; };结构体st2 { uint32_t f1; AlignedType f3; AlignedType f2; }; - platerx

0

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


0
截至于2011年11月16日的Sun C++ 5.12 SunOS_sparc版本中,根据DRH的回复,似乎支持使用gcc语法进行C++编程。
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接