一、定義extern關鍵字
C語言中的extern關鍵字可以用來聲明一個由其他源文件定義的變量、函數或者常量,以便在當前文件中使用。
二、聲明extern關鍵字
在使用extern關鍵字的時候,需要在當前文件中進行聲明,告訴編譯器此變量、函數或常量已在其他源文件中聲明或定義過。
// 外部文件定義變量 int count; // 當前文件聲明extern變量 extern int count;
三、extern關鍵字與全局變量
在C語言中,全局變量默認是擁有extern屬性的,可以被其他文件訪問。因此,只需要在需要訪問該變量的文件中聲明一下即可。
// file1.c 文件中定義全局變量 int count = 0; // file2.c 文件中訪問該全局變量 extern int count; printf("count value is %d", count);
四、extern關鍵字與函數
在C語言中,外部函數也需要使用extern關鍵字進行聲明,以便在當前文件中調用該函數。
// 外部文件定義函數 void func(); // 當前文件聲明extern函數 extern void func(); // 在當前文件中使用該函數 func();
五、extern關鍵字與常量
常量也可以使用extern關鍵字進行聲明。一般在頭文件中定義常量,在其他文件中使用時進行聲明。
// const.h 文件中定義常量 extern const int count; // file2.c 文件中聲明該常量 #include "const.h"
六、extern關鍵字的注意點
在使用extern關鍵字時需要注意以下幾點:
1、在定義變量或函數時,如果沒有指定extern關鍵字,則默認為extern屬性。
2、extern關鍵字只能用於對變量、常量或函數的聲明,不可以用於定義。
3、在同一個文件中不要使用extern關鍵字。
七、完整代碼示例
// const.h extern const int count; // file1.c #include "const.h" int count = 0; // file2.c #include "const.h" #include void func() { printf("This is a external function."); } int main() { printf("count value is %d\n", count); func(); return 0; }
原創文章,作者:ZKNG,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/143665.html