extern

聲明用於向程序表明變量的類型和名字。定義也是聲明:當定義變量時我們聲明瞭它的類型和名字。可以通過使用extern關鍵字聲明變量名而不定義它。不定義變量的聲明包括對象名、對象類型和對象類型前的關鍵字extern:

extern int i; // declares but does not define i
int i; // declares and defines i



An extern declaration is not a definition and does not allocate storage. In effect, it claims that a definition of the variable exists elsewhere in the program. A variable can be declared multiple times in a program, but it must be defined only once.

extern 聲明不是定義,也不分配存儲空間。事實上,它只是說明變量定義在程序的其他地方。程序中變量可以聲明多次,但只能定義一次。

A declaration may have an initializer only if it is also a definition because only a definition allocates storage. The initializer must have storage to initialize. If an initializer is present, the declaration is treated as a definition even if the declaration is labeled extern:

只有當聲明也是定義時,聲明纔可以有初始化式,因爲只有定義才分配存儲空間。初始化式必須要有存儲空間來進行初始化。如果聲明有初始化式,那麼它可被當作是定義,即使聲明標記爲 extern:

extern double pi = 3.1416; // definition

Despite the use of extern, this statement defines pi. Storage is allocated and initialized. An extern declaration may include an initializer only if it appears outside a function.

雖然使用了 extern ,但是這條語句還是定義了 pi,分配並初始化了存儲空間。只有當 extern 聲明位於函數外部時,纔可以含有初始化式。

Because an extern that is initialized is treated as a definition, any subseqent definition of that variable is an error:

因爲已初始化的 extern 聲明被當作是定義,所以該變量任何隨後的定義都是錯誤的:

extern double pi = 3.1416; // definition
double pi; // error: redefinition of pi

Similarly, a subsequent extern declaration that has an initializer is also an error:

同樣,隨後的含有初始化式的 extern 聲明也是錯誤的:

extern double pi = 3.1416; // definition
extern double pi; // ok: declaration not definition
extern double pi = 3.1416; // error: redefinition of pi

The distinction between a declaration and a definition may seem pedantic but in fact is quite important.

聲明和定義之間的區別可能看起來微不足道,但事實上卻是舉足輕重的。

In C++ a variable must be defined exactly once and must be defined or declared before it is used.

在 C++ 語言中,變量必須且僅能定義一次,而且在使用變量之前必須定義或聲明變量。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章