2011-08-30 49 views
6

以下标识符没有链接:声明为除对象或函数以外的任何其他标识符的标识符;一个标识符被声明为一个函数参数; 未声明存储类说明符extern的对象的块范围标识符。块范围链接C标准

{ 
    static int a; //no linkage 
} 

对于在一个范围,其中该标识符的先前声明是可见的,如果事先声明指定的内部或外部联动,标识符中的连杆的存储类说明的extern声明的标识符后面的声明与先前声明中指定的链接相同。如果前面的声明不可见,或者如果先前的声明没有指定链接,那么标识符具有外部链接

{ 
    static int a; //no linkage 
    extern int a; //a should get external linkage, no? 
} 

GCC错误:一个extern声明如下声明没有联动

有人可以解释我为什么我得到这个错误?

谢谢

+1

可能是语义,“指定没有连锁”相对于“指定‘没有连锁’”。在这种情况下自动宣传听起来很疯狂 –

+0

我不明白区别。你能详细说明一下吗? – mindless

回答

8

你的推测是正确的:a的第二个声明有外部链接。

3 If an identifier has no linkage, there shall be no more than one declaration of the identifier (in a declarator or type specifier) with the same scope and in the same name space, except for tags as specified in 6.7.2.3.

也就是说,一旦你已经声明a有没有联系,你不能再在同一范围内重新声明它:不过,你是因为你的代码违反§6.7约束得到一个错误。


被调用该规则的一个有效的例子是:

int a = 10; /* External linkage */ 

void foo(void) 
{ 
    int a = 5; /* No linkage */ 

    printf("%d\n", a); /* Prints 5 */ 

    { 
     extern int a; /* External linkage */ 

     printf("%d\n", a); /* Prints 10 */ 
    } 
} 
+1

您能给我一个有效的例子:如果之前的声明没有指定链接,那么该标识符具有外部链接。我想不出任何。 – mindless

+0

@mindless:我在我的答案中添加了一个示例。 – caf

2

if the prior declaration specifies no linkage

意味着

if the prior declaration specifies not a sign of linkage

,而不是

if the prior declaration specifies that it has no linkage

这是混乱和不明确;不是通常编写标准的方法...

+0

您可以删除静态,错误仍然存​​在。块范围内的静态不会改变链接,只会影响存储时间。在文件范围中,它确实改变了链接,但不改变存储持续时间(总是静态的)。 c另一个含糊之处。 – mindless

+0

你错了;正如它所写的那样,意图是最后一个意思。无论如何,它对问题没有影响。 – caf