C/C++: extern, static, const用法
extern用法
- 為了讓多個檔案能存取同個變數,C++區分宣告(Declaration)以及定義(Definition)。
- 變數可以宣告很多次,但只能定義一次。
可以使用extern宣告而不定義。
如果出現初值,就被當作定義式,即使被標示為extern
宣告方式:
Reference: C++ Primer 4/e p. 52
function使用也是相同的。
如果想在main.c使用在foo.c中定義的void foo(),只需要extern宣告:
static用法
- static出現在區域變數前。
- static variable存活時間和整個程式一樣長,在編譯時就配有固定的記憶體空間,scope則維持不變,即function結束為止。
- 若funtion再次被呼叫,其值會被保留下來。
- static出現在funtion或是全域變數前。
- static可以侷限變數/函式只在本檔案使用,如此就不會被extern拿來連結。
- class的使用
References:
[1]
https://medium.com/@alan81920/c-c-中的-static-extern-的變數-9b42d000688f
[2] http://kamory0931.pixnet.net/blog/post/119201381
[3] https://openhome.cc/Gossip/CGossip/Scope.html
const用法
- 使物件變成常數。
- 預設下const物件為local to file。
- 在global定義一nonconst,另一檔案也可使用(extern用法)。除非有指明,否則golbal域下宣告的const只能在所在的檔案可見。
- 可以將const物件指明為extern,使其在其他檔案也可使用。
References: C++ Primer 4/e p.57