Alignment in SunStudio C++ compiler

516 views Asked by At

I need to declare type alias for 2 bytes variable aligned by 4 bytes.

In GCC, XL C/C++ (AIX), aCC (HP-UX) I can use this code:

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

In Windows I can use:

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

How can I declare same type in SunStudio C++ 11?

"pragma align" isn't suitable because it works only for global or static variable and It requires variable name.

4

There are 4 answers

0
spraff On

For future references, when the compilers catch up, C++11 has standard alignment attributes, see alignas ([dcl.align] in N3242).

1
unwind On

It might be worth at least trying:

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

This of course makes accessing a bit more painful, and kills direct assignment so it might break your entire code base. Also, it's purely based on the assumption that including a larger type, which is assumed to have "native alignment" of 32 bits due to being of that size, makes the union as a whole align on 32 bits.

0
DRH On

As of Sun C 5.9 (Sun ONE Studio 12), the aligned attribute is supported:

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

Unfortunately this attribute is not supported in C++ (at least through Sun C++ 5.10).

0
fuzzyBSc On

As of Sun C++ 5.12 SunOS_sparc 2011/11/16, the gcc syntax appears to be supported for C++ as per DRH's response:

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;

The output is:

8 4 2