C extern關鍵字理解

2022-07-23 07:57:10 字數 2347 閱讀 4410

extern是一種「外部宣告」的關鍵字,字面意思就是在此處宣告某種變數或函式,在外部定義

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

extern關鍵字的主要作用是擴大變數/函式的作用域,使得其它原始檔和標頭檔案可以復用同樣的變數/函式,也起到類似「分塊儲存」的作用,劃分**。如圖所示,在乙個標頭檔案裡做了外部宣告,就能把變數的定義部分和函式體的實現部分轉移到其它地方了。

extern宣告的格式如下,只是在變數宣告時前面加上個」extern「:

extern

inta;

extern

double

b;extern

const

struct box *box_ptr

extern

double box_volume(box box_ptr)

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

主函式:

//

main.cpp

#include

#include

"box_manu.h

"using

namespace

std;

intmain()

extra.h裡定義了box的結構體,做了相關變數和函式的外部宣告。

//

extra.h

struct

box;

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

#include

"extra.h

"using

namespace

std;

box new_box;

double

box_volume(box box_ptr)

double

box_length;

double

box_width;

double

box_height;

void

make_box()

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

//

box_manu.h

#include

#include

"extra.h

"void

bigger_box()

程式執行結果:

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去掉後編譯就會報「重定義」的錯。

C extern 關鍵字詳解

extern關鍵字的用法有如下幾種 一 引入其它檔案中定義的全域性變數或函式 不能是static修飾的,因為static修飾的變數或函式的作用域只存在於當前檔案 比如 在a.c檔案中定義了乙個全域性變數和函式 int num 5 intfunca 若想在b.c檔案中引用a.c檔案裡的全域性變數與函式...

c extern關鍵字的使用

作用 宣告外部符號 使用其他檔案的全域性變數 原始檔 test.c include extern int year 使用extern關鍵字從add.c原始檔中宣告外部符號的全域性變數 int main add.c int year 2022 宣告全域性變數static修飾全域性變數,使得這個全域性變...

this關鍵字理解

public class test implements runnable synchronized void m1 throws interruptedexception synchronized void m2 throws interruptedexception override publi...