在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;
#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会加速程序的编译过程,这样能节省时间。
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;
}
#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会加速程序的编译过程,这样能节省时间。