2011-08-30 48 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