为什么在使用 clang 进行静态声明时,alignas 无法编译?

blu*_*eck 5 c++ static clang language-lawyer alignas

我在 clang 上遇到编译错误,并使用以下代码对 gcc 发出警告:

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
Run Code Online (Sandbox Code Playgroud)

有谁知道为什么在包含 static 关键字的声明中不接受alignas?我将 --std=c++11 编译器选项与 gcc 和 clang 一起使用。(编辑:我使用 clang 3.4 及更高版本和 gcc 4.8 及更高版本)

请注意,使用 Visual Studio (CL 19 RC) 进行编译时,在类似的静态声明中使用alignas 时,我不会收到错误。

use*_*570 1

static alignas(16) int one_s = 1; 根据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 ; 
Run Code Online (Sandbox Code Playgroud)

接下来我们进入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
Run Code Online (Sandbox Code Playgroud)

现在,以上两条规则都不允许static alignas(16) int


解决方案

正确的语法是:

alignas(16) static int one_s = 1;
Run Code Online (Sandbox Code Playgroud)

这次,语法允许了。

simple-declaration:
   decl-specifier-seq init-declarator-listopt ;
   attribute-specifier-seq decl-specifier-seq init-declarator-list ; //this is used now
   ^^^^^^^^alignas^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

接下来我们继续:

 decl-specifier-seq:
   decl-specifier attribute-specifier-seqopt
   decl-specifier decl-specifier-seq      <--------this is used here
   ^^^^static^^^^
Run Code Online (Sandbox Code Playgroud)

这是 msvc 错误: MSVC 接受具有 staticalignas(16) int one_s = 1 的无效程序;