C++ 中的 extern 儲存類
extern 儲存類說明符允許您宣告多個原始檔可以使用的物件。extern 宣告使描述的變數可供當前原始檔的後續部分使用。此宣告不會替換定義。該宣告用於描述外部定義的變數。
extern 宣告可以出現在函式外部或塊的開頭。如果宣告描述了一個函式,或者出現在函式外部並描述了一個具有外部連結的物件,則關鍵字 extern 是可選的。
如果識別符號的宣告已存在於檔案範圍內,則在塊中找到的相同識別符號的任何 extern 宣告都引用同一個物件。如果在檔案範圍內不存在識別符號的其他宣告,則該識別符號具有外部連結。
C++ 將 extern 儲存類說明符的使用限制在物件或函式的名稱上。對型別宣告使用 extern 說明符是非法的。extern 宣告不能出現在類範圍內。
您可以按如下方式使用 extern 關鍵字在檔案之間共享變數:
file3.h
extern int global_variable; /* Declaration of the variable */
file1.c
#include "file3.h" /* Declaration made available here */ #include "prog1.h" /* Function declarations */ /* Variable defined here */ int global_variable = 37; /* Definition checked against declaration */ int increment(void) { return global_variable++; }
file2.c
#include "file3.h" #include "prog1.h" #include <stdio.h> void use_it(void) { printf("Global variable: %d\n", global_variable++); }
stackoverflow 上的以下問題完全抓住了 extern 關鍵字的本質:https://stackoverflow.com/questions/1433204/how-do-i-use-extern-to-share-variables-between-source-files.
廣告