C++ extern淺析
阿新 • • 發佈:2022-03-07
extern是外部宣告關鍵字,字面意思就是宣告某種變數或函式,在外部定義。
extern宣告變數的兩種方法
1.在其他檔案中直接extern
1 #include<iostream> 2 #include<vector> 3 using namespace std; 4 extern int a ; 5 6 int main() { 7 cout << a << endl; 8 return 0; 9 }
1 #include<iostream> 2 #include"test.h" 3using namespace std; 4 int a = 0;
2.在原始檔中定義,標頭檔案中使用extern宣告,然後使用其他檔案直接包含標頭檔案
1 #include<iostream> 2 #include<vector> 3 #include"test.h" 4 using namespace std; 5 6 int main() { 7 cout << a << endl; 8 return 0; 9 }
1 /* test.h */ 2 3 #ifndef_TEST_H_4 #define_TEST_H_ 5 6 extern int a; 7 8 #endif
1 #include<iostream> 2 #include"test.h" 3 using namespace std; 4 int a = 0;
注意:以下是錯誤示範,編譯器會報錯顯示變數a被重定義
1 #include<iostream> 2 #include<vector> 3 #include"test.h" 4 using namespace std; 5 6 int main() { 7 cout << a << endl;8 return 0; 9 } 10 點選並拖拽以移動 11 /* test.h */ 12 13 #ifndef_TEST_H_ 14 #define_TEST_H_ 15 16 int a;//標頭檔案中定義變數,原始檔中使用變數 17 18 #endif
1 /* test.h */ 2 #ifndef_TEST_H_ 3 #define_TEST_H_ 4 5 int a;//標頭檔案中定義變數,原始檔中使用變數 6 #endif
1 #include<iostream> 2 #include"test.h" 3 using namespace std; 4 a = 0;
有兩個原始檔包含了標頭檔案,編譯階段會因為兩次定義變數a而報錯。