声明与定义
首先讲一下声明与定义
声明不等于定义,声明只是指出了变量的名字,并没有为其分配存储空间;定义指出变量名字同时为变量分配存储空间,定义包含了声明
extern int i; //声明变量i,但没分配存储空间,还不能使用, 可以出现很多次,下面的三种情况只能出现一次
int i;//定义了变量i,并分配了空间,可以使用
extern int a =0 //定义一个全局变量a 并给初值
int a =0;//定义一个全局变量a,并给初值
注意:在程序中一个变量可以声明多次,但只能定义一次。
全局变量:在函数内部定义的变量称为局部变量,它的作用域是从定义处到函数结束;在函数外部定义的称为全局变量,它的作用域是从定义处直到文件结束。
不管是全局变量还是局部变量,作用域都是从定义处开始的
extern
extern是用来声明全局变量的
#include
usingnamespacestd;
intmain(){
externinta;
cout<
//inta=5;thisiswrong,ashouldbeaglobalvariable
getchar();
return0;
}
inta=5;//globalvariable
用#include可以包含其他头文件中变量、函数的声明,为什么还要extern关键字?如果我想引用一个全局变量或函数a,我只要直接在源文件中包含#include (xxx.h包含了a的声明)不就可以了么,为什么还要用extern呢?
test.h
#include
usingnamespacestd;
intchangea();
//inttemp2=1;如果在此定义temp2的情况下,main.cpp和test.cpp都包含了test.h,会造成temp2的重复定义
externinttemp3;
test.cpp
#include"test.h"
inttemp1=1000;
//inttemp2=10;如果不注释掉会出错
inttemp3=100;
externconstinttemp4=400;//const默认是局部变量,即使是在全局中申明也一样,且在定义时,必须赋予初值。若想在外部引用,必须加extern
main.cpp
#include
#include
#include"test.h"
usingnamespacestd;
intmain(intargc,char*argv[])
{
externinttemp1;
cout<
externinttemp4;
cout<
//externinttemp2;
//cout<
cout<
system("PAUSE");
returnEXIT_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