C/C++ 中的 extern 的變數範例
C/C++ 中的 extern 的變數範例
資料來源: https://medium.com/@alan81920/c-c-%E4%B8%AD%E7%9A%84-static-extern-%E7%9A%84%E8%AE%8A%E6%95%B8-9b42d000688f
CodeBlocks 12.11
module1.cpp
#include <iostream> #include "module1.h" using namespace std; int a = 1; void greeting() { cout << "Hello World!" << endl; cout << "In greeting, a = " << a << endl; }
module1.h
#ifndef MODULE1_H_INCLUDED #define MODULE1_H_INCLUDED extern int a; void greeting(); #endif // MODULE1_H_INCLUDED
main.cpp:
#include <iostream> #include "module1.h" using namespace std; int main() { greeting(); cout << "In main, a = " << a << endl; cout << endl; a = 0; cout << "In main, a = " << a << endl; greeting(); return 0; } /* Hello World! In greeting, a = 1 In main, a = 1 In main, a = 0 Hello World! In greeting, a = 0 */