C 語言中 static、extern、函數指標(指標函數)是控制**儲存期**、**連結屬性**與**程式碼複用**的核心機制。搞懂它們,等於掌握了模組化設計與底層記憶體模型的鑰匙。
| 語境 | 關鍵字位置 | 效果 | 儲存期 | 連結屬性 | 作用域 |
|---|---|---|---|---|---|
| 區域變數 | 函數內部 | 延長生命週期至程式結束,僅初始化一次 | 靜態 | 無連結 | 區塊 |
| 全域變數 | 函數外部 | 限制本編譯單元(.c 檔)可見 | 靜態 | 內部連結 | 檔案 |
| 函數 | 回傳型別前 | 限制本編譯單元可見,隱藏實作細節 | — | 內部連結 | 檔案 |
// file1.c
static int fileScope = 10; // 僅 file1 可見
static void internalHelper() { } // 僅 file1 可呼叫
void publicApi() {
static int callCount = 0; // 保持跨呼叫狀態
callCount++;
internalHelper();
}
// file2.c
extern int fileScope; // 編譯錯誤:fileScope 為 internal linkage
extern void internalHelper(); // 編譯錯誤
extern(外部連結),除非加 static。// common.h
#ifndef COMMON_H
#define COMMON_H
extern int g_configValue; // 宣告
extern void InitConfig(void); // 宣告(函數 extern 可省略)
#endif
// common.c
#include "common.h"
int g_configValue = 42; // 定義(配置記憶體)
void InitConfig(void) { g_configValue = 100; }
// main.c
#include "common.h"
#include
int main() {
InitConfig();
printf("%d\n", g_configValue); // 100
}
// 定義在 main() 之後,但透過 extern 提前宣告即可使用
#include
void main() {
extern int a, b; // 擴展作用域至 main 之前
printf("a=%d,b=%d", a, b);
}
int a = 13, b = 5;
返回類型 (*指標名稱)(參數列表);
// 範例:int (*cmp)(const void*, const void*); // qsort 比較函數指標
#include
#include
// 版本 1:回傳靜態緩衝區(非執行緒安全,連續呼叫會覆蓋)
char* SubString_Static(const char* s, int start, int end)
{
static char buf[100]; // static 延長儲存期
int len = end - start + 1;
if (len >= 100) len = 99;
strncpy(buf, s + start, len);
buf[len] = '\0';
return buf;
}
// 版本 2:呼叫端提供緩衝區(執行緒安全、零拷貝)
void SubString_Out(const char* s, char* outBuf, size_t bufSize, int start, int end)
{
int len = end - start + 1;
if (len >= bufSize) len = bufSize - 1;
strncpy(outBuf, s + start, len);
outBuf[len] = '\0';
}
// 版本 3:函數指標回呼處理每個字元(策略模式雛形)
typedef void (*CharHandler)(char c, void* ctx);
void ForEachChar(const char* s, int start, int end, CharHandler handler, void* ctx)
{
for (int i = start; i <= end && s[i]; i++)
handler(s[i], ctx);
}
void PrintChar(char c, void* ctx) { putchar(c); }
void CountChar(char c, void* ctx) { (*(int*)ctx)++; }
int main()
{
const char* str = "I Love C Language";
printf("Static: %s\n", SubString_Static(str, 2, 9)); // Love C L
char buf[20];
SubString_Out(str, buf, sizeof(buf), 2, 9);
printf("OutBuf: %s\n", buf);
int cnt = 0;
ForEachChar(str, 0, strlen(str)-1, CountChar, &cnt);
printf("Total chars: %d\n", cnt);
return 0;
}
| 宣告 | 讀法 | 不可修改對象 |
|---|---|---|
const int* p / int const* p | 指向 const int 的指標 | *p(指向的值) |
int* const p | const 指標指向 int | p(指標本身) |
const int* const p | const 指標指向 const int | p 與 *p 皆不可修改 |
**口訣**:const修飾右側實體;若右側為*則修飾指標,否則修飾型別。
static 區域變數在遞迴/多執行緒中共享狀態 → 改用參數傳遞或執行緒區域儲存。extern 重複定義 → 僅在**一個** .c 定義,頭檔只 extern 宣告。NULL,呼叫前檢查。void* context 傳遞狀態,支援閉包模擬。static 控制**可見範圍與生命週期**,extern 建立**跨模組契約**,函數指標實現**執行期多態與回呼**。三者結合,構成 C 語言模組化、擴展性與效能的鐵三角。