Best cross-platform alignment macro?

Viewed 85
__declspec(align(X))
__attribute((aligned(X)))

These are the two I've come across. Are they the only two ways that compilers deal with alignment?

If I target C11, will alignas(X) accomplish the same thing and is it implemented in all C11 supporting compilers? On macOS using clang it seems alignas(X) doesn't work with typedefs?

typedef alignas(16) float vec4[4];
error: '_Alignas' attribute only applies to variables and fields
        ^
1 Answers

The problem is not with your clang on macOS but with the other compiler(s) allowing alignas() (actually a macro for _Alignas() in C)1 on the typedef (presumably, as an extension).

From cppreference (bolding mine):

The _Alignas specifier can only be used when declaring objects that aren't bit fields, and don't have the register storage class. It cannot be used in function parameter declarations, and cannot be used in a typedef.

Or, from this Draft C11 Standard:

6.7.5 Alignment specifier


Constraints
2     An alignment attribute shall not be specified in a declaration of a typedef, or a bit-field, or a function, or a parameter, or an object declared with the register storage-class specifier.


1 The alignas keyword was introduced to C++ at the C++11 Standard; ISO C11 added it as an 'alias' of the _Alignas keyword. From the cppreference for the C++ version:

As of the ISO C11 standard, the C language has the _Alignas keyword and defines alignas as a preprocessor macro expanding to the keyword in the header <stdalign.h>.

Related