首先讲一下声明与定义ios
声明不等于定义,声明只是指出了变量的名字,并无为其分配存储空间;定义指出变量名字同时为变量分配存储空间,定义包含了声明函数
extern int i; //声明变量i,但没分配存储空间,还不能使用, 能够出现不少次,下面的三种状况只能出现一次this
int i; //定义了变量i,并分配了空间,可使用spa
extern int a =0 //定义一个全局变量a 并给初值code
int a =0;//定义一个全局变量a,并给初值作用域
注意:在程序中一个变量能够声明屡次,但只能定义一次。get
全局变量:在函数内部定义的变量称为局部变量,它的做用域是从定义处到函数结束;在函数外部定义的称为全局变量,它的做用域是从定义处直到文件结束。io
无论是全局变量仍是局部变量,做用域都是从定义处开始的编译
extern是用来声明全局变量的class
#include<iostream> using namespace std; int main(){ extern int a; cout<<a<<endl; //int a=5; this is wrong , a should be a global variable getchar(); return 0; } int a=5;//global variable
用#include能够包含其余头文件中变量、函数的声明,为何还要extern关键字?若是我想引用一个全局变量或函数a,我只要直接在源文件中包含#include<xxx.h> (xxx.h包含了a的声明)不就能够了么,为何还要用extern呢?
test.h
#include<iostream> using namespace std; int changea(); //int temp2=1; 若是在此定义temp2的状况下,main.cpp和test.cpp都包含了test.h,会形成temp2的重复定义 extern int temp3;
test.cpp
#include "test.h" int temp1=1000; //int temp2=10; 若是不注释掉会出错 int temp3=100; extern const int temp4=400;//const默认是局部变量,即便是在全局中申明也同样,且在定义时,必须赋予初值。若想在外部引用,必须加extern
main.cpp
#include <cstdlib> #include <iostream> #include "test.h" using namespace std; int main(int argc, char *argv[]) { extern int temp1; cout<<"temp1 is"<<temp1<<endl; extern int temp4; cout<<"temp4 is"<<temp4<<endl; //extern int temp2; //cout<<"temp2 is"<<temp2<<endl; cout<<"temp3 is"<<temp3<<endl; system("PAUSE"); return EXIT_SUCCESS; }
output:
temp1 is1000
temp4 is400
temp3 is100
temp1: 在test.cpp中声明 int temp1=1000, 在main.cpp中使用temp1,首先声明temp1是一个外部变量
temp2:在test.h中定义,main.cpp和test.cpp都包含了test.h,会形成temp2的重复定义,注释掉程序才能经过编译
temp3:在test.h中声明,在test.cpp中定义,在main.cpp中使用
temp4:const默认是局部变量,即便是在全局中申明也同样,且在定义时,必须赋予初值。若想在外部引用,必须加extern
总之原则就是:要想使用其余文件的一个全局变量,就必须定义extern type variablename,而后才能使用
若是const变量想被其余文件使用,在定义的前面须要添加extern