聊聊“extern”關鍵字

在C語言中,修飾符extern用在變量或者函數的聲明前,用來說明“此變量/函數是在別處定義的,要在此處引用”。作用見下:
    1,在C++中extern的作用,用於指示C或者C++函數的調用規範。比如在C++中調用C庫函數,就需要在C++程序中用extern “C”聲明要引用的函數。這是給鏈接器用的,告訴鏈接器在鏈接的時候用C函數規範來鏈接。主要原因是C++和C程序編譯完成後在目標代碼中命名規則不同,用此來解決名字匹配的問題。
// compile with: /c
// Declare printf with C linkage.
extern "C" int printf( const char *fmt, ... );


//  Cause everything in the specified header files
//   to have C linkage.
extern "C" {
   // add your #include statements here
   #include <stdio.h>
}


//  Declare the two functions ShowChar and GetChar
//   with C linkage.
extern "C" {
   char ShowChar( char ch );
   char GetChar( void );
}


//  Define the two functions ShowChar and GetChar
//   with C linkage.
extern "C" char ShowChar( char ch ) {
   putchar( ch );
   return ch;
}
以上程序摘自MSDN

extern "C" char GetChar( void ) {
   char ch;


   ch = getchar();
   return ch;
}
  2,在下面的程序test_1.cpp中,定義一個全局變量 int a = 8,


#include "iostream"
using namespace std;
int a = 8;
int test()
{
 
cout <<"do you get!!!!!"<<endl;
cout<<a<<endl;
system("pause");
return 0;

}


在test_2.cpp中
#include <iostream>
#include "test_1S.cpp"
using namespace std;
int main()
{
extern   a ;
    
cout <<"extern a="<<a<<endl;
return 0;
}
    在上面的例子中可以看出,在test_2中如果想調用test_1中的變量a,只須用extern進行聲明即可調用a,這就是extern的作用。在這裏要注意extern聲明的位置對其作用域也有關係,
如果是在main函數中進行聲明的,則只能在main函數中調用,在其它函數中不能調用。其實要調用其它文件中的函數和變量,只需把該文件用#include包含進來即可,爲啥要用extern?因爲用extern會加速程序的編譯過程,這樣能節省時間。
發佈了28 篇原創文章 · 獲贊 4 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章