c语言extern关键字详解
在c語言中代碼的執(zhí)行順序是從上往下執(zhí)行的,如果定義的函數(shù)或者變量在調(diào)用之后,那么調(diào)用的時候編譯就會找不到需要使用的變量。這樣就會出現(xiàn)錯誤,如下代碼:
#include<stdio.h>int main(){printf("%d",num);function();return 0; }int num =5;void function(){printf(" hello word main function\n"); }執(zhí)行這句代碼就會出現(xiàn)錯誤,錯誤原因就是因為,num和funcion函數(shù)定義在main函數(shù)的下面導(dǎo)致main函數(shù)中執(zhí)行num和function的時候編譯器并沒有編譯到那里所有編譯器就會認(rèn)為沒有定義num和function 函數(shù)所以會出現(xiàn)錯誤。那么我可以使用extern關(guān)鍵字來改正個問題。extern關(guān)鍵字可以 讓變量全局化。
#include<stdio.h>extern int num ; void function();int main(){printf("%d",num);function();return 0; }int num =5;void function(){printf(" hello word main function\n"); }這樣就可以正常運行了。extern 關(guān)鍵字還可以調(diào)用其他.c文件中的變量和函數(shù) 如下:
test_extern.c#include<stdio.h>int num =5; int age=29; char name="make";void func(){printf(" 調(diào)用 test_extern函數(shù)!!\n "); }test_main.c#include<stdio.h>int main(){extern int num ;extern int age;extern char name;extern void func();func();printf("%d\n",num);printf("%d\n",age);pirntf("%s\n",name);return 0; }執(zhí)行上面代碼就可以在test_main文件中打印出test_extern文件中的字段和方法。這樣寫有一個好處就是可以不用再文件中因為別的 .h頭文件,因為如果引用.h頭文件就可以調(diào)用.h文件中所有的函數(shù)和字段,這樣不是很安全,所以如果想代用另外一個.c源文件的函數(shù)時可以使用extern關(guān)鍵字來調(diào)用這樣提高 了函數(shù)的安全性。
總結(jié):extern 有三種用三,在本文件中使變量全局化,調(diào)用其他源文件中的字段,調(diào)用其他源文件中的函數(shù)。
轉(zhuǎn)載于:https://blog.51cto.com/14058389/2339141
總結(jié)
以上是生活随笔為你收集整理的c语言extern关键字详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: window10 java 设置环境变量
- 下一篇: The compiler complia