C 語言四大存儲類別:auto(默認局部)、register(建議寄存器)、static(靜態存儲/內部鏈接)、extern(外部聲明/外部鏈接)。
.c 定義,其他 .c 用 extern 聲明。int foo(); 等價 extern int foo();,通常省略。file1.c(定義)
#include <stdio.h>
#include <stdlib.h>
char str[255]; // 定義:分配空間,外部鏈接
int index_str = 0; // 定義
char getChar(void) { // 定義
return str[index_str++];
}
file2.c(聲明並使用)
#include <stdio.h>
#include <stdlib.h>
extern char str[]; // 聲明:不分配空間,引用 file1.c 的 str
extern int index_str; // 聲明
extern char getChar(void); // 聲明(可省略 extern)
void getStr(const char *filename) {
FILE *fp = fopen(filename, "r");
if (!fp) { perror("open"); exit(1); }
int i = 0;
while ((str[i++] = fgetc(fp)) != EOF);
str[i] = '\0';
fclose(fp);
}
編譯鏈接**:
gcc file1.c file2.c -o app
# 或分步
gcc -c file1.c -o file1.o
gcc -c file2.c -o file2.o
gcc file1.o file2.o -o app
shared.h
#ifndef SHARED_H
#define SHARED_H
extern char str[]; // 變量聲明
extern int index_str;
char getChar(void); // 函數聲明(隱式 extern)
void getStr(const char *); // 函數聲明
#endif
所有需共享的 .c 統一 #include "shared.h",避免重複聲明、類型不一致。
| 錯誤 | 原因 | 修正 |
|---|---|---|
| 多重定義 | 頭文件寫 int g = 0; 定義 | 頭文件只寫 extern int g;,單一 .c 定義 |
| 未定義引用 | 聲明了 extern 但無定義 | 確保恰好一個 .c 定義,且參與鏈接 |
| 類型不匹配 | 不同文件聲明類型不同 | 集中在頭文件聲明,包含頭文件 |
| 靜態變量跨文件 | static int x; 內部鏈接 | 去掉 static 或提供訪問函數 |
// c_lib.h
#ifdef __cplusplus
extern "C" {
#endif
void c_function(int);
#ifdef __cplusplus
}
#endif
強制 C++ 編譯器用 C 名字修飾,使 C++ 代碼能鏈接 C 庫符號。