3

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.

Alexey Kukanov
  • 12,479
  • 2
  • 36
  • 55
platerx
  • 31
  • 1
  • Related, you can also use `__alignof__` to determine alignment for SunCC compilers. It is an extension like GCC's `__alignof__`. It tested good back to SunCC 5.8 on Solaris 9. Thanks to [OpenCSW](https://www.opencsw.org/) for providing access to their [compile farm](https://www.opencsw.org/extend-it/signup/to-upstream-maintainers/) to test old x86 and Sparc machines. – jww Jul 21 '18 at 10:40

4 Answers4

2

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).

DRH
  • 7,868
  • 35
  • 42
1

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.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 1
    It won't work. Variable must be aligned by 4 bytes, but size of variable must be 2 bytes! For example size of st1 must be 8 bytes, but size of st2 must be 12 bytes. struct st1 { uint32_t f1; AlignedType f3; int16_t f2; }; struct st2 { uint32_t f1; AlignedType f3; AlignedType f2; }; – platerx Jan 24 '12 at 10:25
0

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

fuzzyBSc
  • 823
  • 8
  • 7
0

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

spraff
  • 32,570
  • 22
  • 121
  • 229