搜尋
首頁php教程PHP开发全域變數和extern詳解

全域變數和extern詳解

Dec 19, 2016 pm 02:42 PM

聲明與定義

首先講一下聲明與定義

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

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

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)