全局变量和extern详解

声明与定义

首先讲一下声明与定义

声明不等于定义,声明只是指出了变量的名字,并没有为其分配存储空间;定义指出变量名字同时为变量分配存储空间,定义包含了声明

extern  int  i;  //声明变量i,但没分配存储空间,还不能使用, 可以出现很多次,下面的三种情况只能出现一次

int  i;         //定义了变量i,并分配了空间,可以使用

extern int a =0 //定义一个全局变量a 并给初值

int a =0;//定义一个全局变量a,并给初值


注意:在程序中一个变量可以声明多次,但只能定义一次。

全局变量:在函数内部定义的变量称为局部变量,它的作用域是从定义处到函数结束;在函数外部定义的称为全局变量,它的作用域是从定义处直到文件结束。

不管是全局变量还是局部变量,作用域都是从定义处开始的


extern

extern是用来声明全局变量的

#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

转载于:https://my.oschina.net/hnuweiwei/blog/291037

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值