EXTERN
extern 儲存類說明符可以通過以下三種方式之一修改宣告,具體取決於上下文:
-
它可用於在不定義變數的情況下宣告變數。通常,這將在標頭檔案中用於將在單獨的實現檔案中定義的變數。
// global scope int x; // definition; x will be default-initialized extern int y; // declaration; y is defined elsewhere, most likely another TU extern int z = 42; // definition; "extern" has no effect here (compiler may warn) -
它為名稱空間範圍內的變數提供外部連結,即使
const或constexpr會導致它具有內部連結。// global scope const int w = 42; // internal linkage in C++; external linkage in C static const int x = 42; // internal linkage in both C++ and C extern const int y = 42; // external linkage in both C++ and C namespace { extern const int z = 42; // however, this has internal linkage since // it's in an unnamed namespace } -
如果之前使用連結宣告它,則在塊範圍內重新宣告變數。否則,它宣告一個帶有連結的新變數,該變數是最近的封閉名稱空間的成員。
// global scope namespace { int x = 1; struct C { int x = 2; void f() { extern int x; // redeclares namespace-scope x std::cout << x << '\n'; // therefore, this prints 1, not 2 } }; } void g() { extern int y; // y has external linkage; refers to global y defined elsewhere }
函式也可以宣告為 extern,但這沒有效果。它通常用作讀者的提示,這裡宣告的函式是在另一個翻譯單元中定義的。例如:
void f(); // typically a forward declaration; f defined later in this TU
extern void g(); // typically not a forward declaration; g defined in another TU
在上面的程式碼中,如果 f 被改為 extern 而 g 改為 non-extern,它根本不會影響程式的正確性或語義,但可能會使程式碼的讀者感到困惑。