Global Variables in C and C++
先簡單的介紹一下 C 與 C++ 處理 global variable initialization 的差異. 下面的 code snip 定義了四個 non-auto variable, 它們的 life scope 都 (可以) 是全局的, 要到程式 termination 才結束. 因此它們都可算是 實質上的 global variable, 本文也將以 global variable 稱之:
int global_1 = 1;
int* foo()
{
static int global_2 = 1;
return &global_2;
}
int global_3 = *foo();
int* bar()
{
static int global_4 = *foo();
return &global_4;
}
以 GCC 為例, 這段 code 可以合法地當作 C++ source code 編譯:
freak@blizzard:~/tmp$ # when compiled as C++, it went just fine. freak@blizzard:~/tmp$ freak@blizzard:~/tmp$ gcc -x c++ -c globals.c freak@blizzard:~/tmp$
卻會被 C compiler 拒絕:
freak@blizzard:~/tmp$ # when compiled as good old C, compiler complains. freak@blizzard:~/tmp$ freak@blizzard:~/tmp$ gcc -x c -c globals.c globals.c:9: error: initializer element is not constant globals.c: In function ‘bar’: globals.c:13: error: initializer element is not constant freak@blizzard:~/tmp$
