extern
extern外部全域變數
想使用其它.c或.cpp中的全域變數,使用extern。
以下是test.cpp
1
2
#include <stdio.h>
int num = 100;
以下是main.cpp
main.cpp要使用test.c的全域變數num,main.cpp要使用extern,把其它檔案的全域變數引入。
extern 類型 其它檔案全域變數名;
1
2
3
4
5
extern int num;
int main() {
cout << num << endl;
return 0;
}
100
不能有同名的全域變數,使用外部全域變數,不能再定義同名的全域變數,以下編譯錯誤。
1
2
3
4
5
6
extern int num;
int num = 20;
int main() {
cout << num << endl;
return 0;
}
extern函式()
要使用其它檔案中的函式,除了include之外,也可以使用extern 函式()。
以下是main2.cpp
1
2
3
4
#include <stdio.h>
void main2() {
printf("call extern test() \n");
}
以下是main.cpp。
extern 傳回類型 外部函式();
1
2
3
4
5
extern void main2();
int main() {
main2();
return 0;
}
call extern test()
extern 靜態全域變數
靜態全域變數,無法共享給其它檔案,存取範圍只有宣告靜態全域變數的cpp或c檔案才可以用。
不支持extern 靜態全域變數,執行時會失敗。
以下是main2.cpp
1
2
3
#include <stdio.h>
// 靜態全域變數
static int counter = 500;
以下是main.cpp,使用extern 靜態變數執行會失敗。
1
2
3
4
5
extern int counter;
int main() {
cout << counter << endl;
return 0;
}
extern 靜態函式
靜態函式,無法共享給其它檔案,存取範圍只有宣告靜態函式的cpp或c檔案才可以用。
不支持extern 靜態函式,執行時會失敗。
以下是main2.cpp
1
2
3
4
static int counter = 500;
static void main2() {
printf("call extern test() \n");
}
以下是main.cpp
1
2
3
4
5
extern void main2();
int main() {
main2();
return 0;
}