为什么 "const extern" 报错?

Why does "const extern" give an error?

以下代码运行良好:

#include <stdio.h>

extern int foo; // Without constant
int foo = 42;

int main() 
{
    printf("%d\n",foo);
    return 0;
}

但是,下面的一段代码报错了:

#include <stdio.h>

const extern int foo; // With constant
int foo = 42;

int main() 
{
    printf("%d\n",foo);
    return 0;
}

那么,为什么const extern报错呢?

标准说:
C11-§6.7/4

All declarations in the same scope that refer to the same object or function shall specify compatible types

const intint 对于同一范围内的同一对象 foo 不兼容。

这两个声明是矛盾的:

const extern int foo; // With constant
int foo = 42;

第一个声明foo为const,第二个声明为非const。

错误信息:

prog.cpp:4:5: error: conflicting declaration
   ‘int foo’ int foo = 42; 
         ^~~
 prog.cpp:3:18: note: previous declaration as ‘const int foo’
    const extern int foo; // With constant 
                     ^~~

你说 fooconst 然后尝试用另一个声明改变它的常量。 这样做,你应该没问题。

  const extern int foo; // With constant
  const int foo = 42;