C 語言中所有函數預設為外部連結,但透過 extern 和 static 關鍵字可精確控制函數的可見範圍,實現模組封裝與命名空間隔離。
extern int add(int a, int b); // 宣告(通常在頭檔)
int add(int a, int b) { ... } // 定義(在 .c 檔)
externextern),否則編譯器假設回傳 int 導致錯誤static int helper(int x) { ... } // 僅本檔案可見
static 函數staticundefined reference| 場景 | 建議 | 範例 |
|---|---|---|
| 公開 API | 頭檔 extern 宣告,.c 定義不加關鍵字 | int api_init(void); |
| 內部輔助函數 | .c 檔頂部 static 定義 | static void internal_cleanup(void); |
| 單一檔案程式 | 所有函數 static 除 main | 避免符號洩漏 |
| 庫開發 | 最小化公開符號,內部全 static | 減少連結衝突、提升載入速度 |
static 僅影響連結可見性,不影響呼叫機制