Skeen
Skeen

Reputation: 4722

alignas specifier vs __attribute__(aligned), c++11

I'm currently in the process of developing an OS kernel in C++11, and I've come across a question, I cannot seem to find the answer to myself.

Currently I'm aligning my paging structures, using compiler specific attributes (eg. gcc's __attribute__(aligned)), however I'm wanting to use the C++11 alignas specifier instead, on Clang++ this is no issue, as it gladly accepts 4096 alignment as parameter to alignas, however G++ does not!

So first of all, what's the main difference between the alignas specifier, and the gcc __attribute__(aligned), obviously both ensure alignment to a specific value, however the alignas specifier in gcc seems to have a limit of 128, while the attribute seems almost limitless, why is this?

Also why can't one pass a const integer to the alignas specifier?

Upvotes: 14

Views: 10838

Answers (2)

rjhcnf
rjhcnf

Reputation: 1057

They are different in terms of where it can be positioned. attribute(aligned) can be put as return type of function but alignas cannot be. Semantically they are same.

Upvotes: 0

Thibaut
Thibaut

Reputation: 2420

It seems from the GCC support status, alignment support is not fully supported in gcc 4.7, but it is for gcc 4.8. alignas is also listed as a newly supported feature from the 4.8 release page.

Also, from the alignment support proposal (3.11):

A fundamental alignment is represented by an alignment less than or equal to the greatest alignment supported by the implementation in all contexts, which is equal to alignof(std::max_align_t) (18.1).

An extended alignment is represented by an alignment greater than alignof(std::max_align_t). It is implementation-defined whether any extended alignments are supported and the contexts in which they are supported (7.1.6). A type having an extended alignment requirement is an over-aligned type.

And from the same document (7.1.6):

if the constant expression evaluates to an extended alignment and the implementation does not support that alignment in the context of the declaration, the program is illformed

That might be part of the answer too. I don't have access to the full standard at the moment, someone should be able to confirm this.

As for the difference between __attribute__(aligned) and alignas, i don't think they are semantically different, but one is just a compiler extension while the other is fully defined by the standard.

To answer your last question, alignas is only defined for:

alignas ( constant-expression ) 
alignas ( type-id ) 

Upvotes: 7

Related Questions