聊聊“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会加速程序的编译过程,这样能节省时间。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值