C++extern關鍵字理解


extern是一種“外部聲明”的關鍵字,字面意思就是在此處聲明某種變量或函數,在外部定義

下面的示意圖是我的理解。

extern關鍵字的主要作用是擴大變量/函數的作用域,使得其它源文件和頭文件可以復用同樣的變量/函數,也起到類似“分塊儲存”的作用,划分代碼。如圖所示,在一個頭文件里做了外部聲明,就能把變量的定義部分和函數體的實現部分轉移到其它地方了。

extern聲明的格式如下,只是在變量聲明時前面加上個”extern“:

extern int a;
extern double b;
extern const struct box *box_ptr 
extern double box_volume(box box_ptr)

 

下面是個例子,程序提示用戶輸入一個盒子的長寬高,存儲在結構體內,然后用函數輸出該盒子的體積,再用一個函數將盒子的三維長度擴大一倍,最后再次輸出它的體積。

 

主函數:

//main.cpp

#include<iostream>
#include"box_manu.h"

using namespace std;

int main()
{
    make_box();        //引導用戶輸入一個新盒子的的信息

    cout << "Volume of this box:" << box_volume(new_box) << endl;    //輸出該盒子的體積

    bigger_box();    //把該盒子的三維加一倍

    cout << "done.\n";

    cout << "Bigger volume:" << box_volume(new_box) << endl;    //輸出改造后的體積

    system("pause");
}

 

Extra.h里定義了box的結構體,做了相關變量和函數的外部聲明。

//extra.h

struct box
{
    double length;
    double width;
    double height;
    double volume;

};

extern const struct box        *    box_ptr;

extern box new_box;

extern double box_length;
extern double box_width;
extern double box_height;

extern double box_volume(box box_ptr);

extern void make_box();

 

box_make.cpp里定義了box結構類型的new_box變量,以及長寬高,但沒賦值。給出了輸出體積和提示輸入的函數的原型。

//box_make.cpp

#include<iostream>
#include"Extra.h"
using namespace std;

box new_box;

double box_volume(box box_ptr)
{
    box_ptr.volume = box_ptr.height*box_ptr.length*box_ptr.width;
    return box_ptr.volume;
}

double box_length;
double box_width;
double box_height;

void make_box()
{
    cout << "Input length for the box:";
    cin >> box_length;
    new_box.length = box_length;
    cout << "Input width for the box:";
    cin >> box_width;
    new_box.width = box_width;
    cout << "Input height for the box:";
    cin >> box_height;
    new_box.height = box_height;
}

 

box_manu.h給出了擴大盒子三維的函數原型,並被main.cpp包括。

//box_manu.h

#include<iostream>
#include"Extra.h"

void bigger_box() { new_box.length = 2 * new_box.length; new_box.height = 2 * new_box.height; new_box.width = 2 * new_box.width; }

 

程序運行結果:

Input length for the box:2 [enter]
Input width for the box:2 [enter]
Input height for the box:2 [enter]
Volume of this box:8
done.
Bigger volume:64

  

值得注意的問題:

1.主函數include的box_manu.h已經include了Extra.h,如果再include一遍Extra.h。會報大量不兼容和重定義等錯,應盡力避免重復引用頭文件

2.在extra.h里面聲明的長寬高變量必須要在其它哪里給出定義,哪怕沒有初值(例子中寫到了box_make.cpp里面)。如果沒有這么做,編譯時會報LNK200“無法解析外部命令”的錯。

3.多個頭文件或源文件使用同一些變量,嘗試把extern去掉后編譯就會報“重定義”的錯。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM