Why doesn't alignas compile when used in a static declaration with clang?

1.3k Views Asked by At

I have a compilation error on clang and a warning with gcc with this code:

static alignas(16) int one_s = 1;                      // clang: error: an attribute list cannot appear here; gcc: warning: attribute ignored;
static __attribute__((aligned(16))) int zero_s = 0;    // on the other hand this works well on both compilers...
alignas(16) int one = 1;                               // this also works on both compilers
__attribute__((aligned(16))) int zero = 0;             // as well as this

Does anyone know why alignas is not accepted in the declaration that contains the static keyword? I used the --std=c++11 compiler option with both gcc and clang. (Edit: I used clang 3.4 and above and gcc 4.8 and above)

Note that when compiling with Visual Studio (CL 19 RC) I don't get an error when using alignas in a static declaration like that.

1

There are 1 best solutions below

1
On

static alignas(16) int one_s = 1; is ill-formed as per the grammar rules in simple-declaration:

 simple-declaration:
   decl-specifier-seq init-declarator-listopt ;  <--------this is the case here
   attribute-specifier-seq decl-specifier-seq init-declarator-list ;
   attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ] initializer ; 

Next we move onto decl-specifier-seq:

decl-specifier-seq:
   decl-specifier attribute-specifier-seqopt   //this doesn't match
   decl-specifier decl-specifier-seq           //this doesn't match either

Now, neither of the above two rules allow static alignas(16) int.


Solution

The correct syntax would be:

alignas(16) static int one_s = 1;

This time, the grammar allows it.

simple-declaration:
   decl-specifier-seq init-declarator-listopt ;
   attribute-specifier-seq decl-specifier-seq init-declarator-list ; //this is used now
   ^^^^^^^^alignas^^^^^^^^

Next we move onto:

 decl-specifier-seq:
   decl-specifier attribute-specifier-seqopt
   decl-specifier decl-specifier-seq      <--------this is used here
   ^^^^static^^^^

Here is the msvc bug: MSVC accepts invalid program having static alignas(16) int one_s = 1;