2012-09-11 62 views
0

我寫了下面的代碼無法編輯的extern變量

head.h

int i = 0; 

sample.cpp的

#include <stdio.h> 
#include "head.h" 

extern int i; 
i = 20; 

int main() { 
    printf("%d \n",i); 
    return 0; 
} 
當我編譯sample.cpp的編譯器

拋出以下錯誤:

sample.c:5:1: warning: data definition has no type or storage class [enabled by default] 
sample.c:5:1: error: redefinition of ‘i’ 
head.h:1:5: note: previous definition of ‘i’ was here 

回答

5

這是換句話說,extern聲明應該在頭文件中,並且定義在一個實現文件中並且只定義一次

//head.h 
extern int i; 


//sample.cpp 
#include <stdio.h> 
#include "head.h" 

int i = 20; 

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

可以聲明變量很多次,只要你想,但定義必須是唯一的。

+0

如果我們聲明這種方式並在其他文件中包含頭文件,那麼這兩個文件是否會使用相同的extern變量?如果變量的值在一箇中改變,它會反映在另一箇中? – user1198065

+0

@ user1198065是的。 –

+0

好的謝謝。你還可以告訴我在一個全局變量的情況下外部和靜態變量的行爲有何不同。 – user1198065