全局變量和extern詳解

聲明與定義

首先講一下聲明與定義ios

聲明不等於定義,聲明只是指出了變量的名字,並無爲其分配存儲空間;定義指出變量名字同時爲變量分配存儲空間,定義包含了聲明函數

extern  int  i;  //聲明變量i,但沒分配存儲空間,還不能使用, 能夠出現不少次,下面的三種狀況只能出現一次this

int  i;         //定義了變量i,並分配了空間,可使用spa

extern int a =0 //定義一個全局變量a 並給初值code

int a =0;//定義一個全局變量a,並給初值作用域


注意:在程序中一個變量能夠聲明屢次,但只能定義一次。get

全局變量:在函數內部定義的變量稱爲局部變量,它的做用域是從定義處到函數結束;在函數外部定義的稱爲全局變量,它的做用域是從定義處直到文件結束。io

無論是全局變量仍是局部變量,做用域都是從定義處開始的編譯


extern

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

相關文章
相關標籤/搜索