// global.h int sharedData = 9; // 錯誤!每個包含此頭文件的 .cpp 都會定義一份
編譯錯誤:
global.o:(.data+0x0): `sharedData' 被多次定義 CTest.o:(.data+0x0):第一次在此定義 collect2: 錯誤:ld 返回 1
// global.h extern int sharedData; // 告訴編譯器:此變量在別處定義
// global.cpp #include "global.h" int sharedData = 9; // 真正分配內存、初始化
// CTest.cpp #include "global.h" #includeusing namespace std; int main() { cout << sharedData << endl; // 直接使用 return 0; }
Building file: ../src/CTest.cpp Invoking: GCC C++ Compiler g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/CTest.d" -MT"src/CTest.d" -o "src/CTest.o" "../src/CTest.cpp" Finished building: ../src/CTest.cpp Building file: ../src/global.cpp Invoking: GCC C++ Compiler g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/global.d" -MT"src/global.d" -o "src/global.o" "../src/global.cpp" Finished building: ../src/global.cpp Building target: CTest Invoking: GCC C++ Linker g++ -o "CTest" ./src/CTest.o ./src/global.o Finished building target: CTest
C++ 中 `const` 全局變量默認內部鏈接(等同 `static`),各編譯單元各自一份。若需跨文件共享:
// global.h extern const int MAX_SIZE; // 聲明 // global.cpp const int MAX_SIZE = 100; // 定義,外部鏈接
| 錯誤 | 後果 | 修正 |
|---|---|---|
| 頭文件定義非 const 變量 | 多重定義鏈接錯誤 | 頭文件 `extern` 聲明,源文件定義 |
| 頭文件定義 const 變量 | 各文件各自一份(內部鏈接) | 源文件定義,頭文件 `extern const` 聲明 |
| 忘記包含頭文件 | 編譯錯誤:未聲明標識符 | 使用文件 `#include "global.h"` |
| 源文件未定義 | 鏈接錯誤:未定義引用 | 確保有且僅有一個 .cpp 定義 |
C++ 多文件共享全局變量的核心規則:聲明與定義分離。頭文件只放 `extern` 聲明,源文件放定義初始化。這符合一個定義規則 (ODR),避免鏈接時多重定義錯誤。理解編譯、鏈接兩階段的職責分工,是掌握 C++ 構建系統的基礎。