多文件項目中共享全局變量/數組,核心原則是:一處定義,多處聲明。常見錯誤是將定義寫在函數內部,導致其成為局部變量,其他文件通過 `extern` 找不到符號。
// main.c
int main() {
char* shuzu[] = {"a", "b"}; // ❌ 定義在函數內 → 局部變量
find(match);
}
// find.c
extern char* shuzu[]; // 聲明外部符號
void find(...) { ... shuzu ... } // 鏈接錯誤:找不到 shuzu 定義
// main.c
#include "declare.h"
char* shuzu[] = { "a", "b" }; // ✅ 文件作用域定義,外部鏈接
int main() {
find(match);
return 0;
}
// declare.h
extern char* shuzu[]; // 聲明,供其他 .c 文件包含
// find.c
#include "declare.h"
void find(void (*match)(char*)) { ... shuzu ... } // 正常訪問
| 場景 | 正確寫法 | 錯誤寫法 |
|---|---|---|
| 定義(僅一處) | int g_val = 0; 或 char* arr[] = {...}; 在 .c 文件頂層 | 寫在函數內、寫在 .h 中、多處定義 |
| 聲明(多處可見) | extern int g_val; 在 .h 中 | 漏寫 extern、在 .h 中定義 |
| 數組聲明 | extern char* arr[]; 不需指定大小 | extern char* arr[10]; 非標準 |
gcc main.c find.c match.c -o app