首頁  >  文章  >  php教程  >  全域變數和extern詳解

全域變數和extern詳解

高洛峰
高洛峰原創
2016-12-19 14:42:171517瀏覽

聲明與定義

首先講一下聲明與定義

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

extern  int  i;  //宣告變數i,但沒分配儲存空間,還不能使用, 可以出現很多次,下面的三種情況只能出現一次

int  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包含了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;

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 is100000130 月

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

更多全域變數和extern詳解相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn