在 head.h 中直接定義變數 int ab = 0;,即使有防護巨集 #ifndef HEAD_H,當多個 .cpp 檔包含此頭檔時,每個編譯單元都會產生一個 ab 的定義,連結階段報重複定義錯誤。
頭檔僅宣告:
// head.h
#ifndef HEAD_H
#define HEAD_H
extern int ab; // 僅宣告
#endif在某一個 .cpp 檔定義:
// main.cpp 或其他單一 cpp
#include "head.h"
int ab = 0; // 定義這樣所有檔案共用同一個 ab 實體,避免重複定義。