| 區段 | 內容 | 生命週期 | 範例 |
|---|---|---|---|
| 程式碼區 | 機器指令 | 程式執行期間 | 函數本體 |
| 初始化資料區 | 已賦初值的全域/靜態變數 | 程式執行期間 | int g = 10; |
| 未初始化資料區 | 未賦初值的全域/靜態變數 (BSS) | 程式執行期間 (啟動時歸零) | int g; |
| 堆疊 | 區域變數、函數參數、返回位址 | 函數呼叫期間 | void f() { int a; } |
| 堆積 | 動態配置記憶體 | malloc/free 管理 | malloc(100) |
// file1.c
static int g_count = 0; // 僅本檔案可見
static void helper() { ... } // 僅本檔案可呼叫
int public_api() { // 外部連結,預設
g_count++;
helper();
return g_count;
}
效果:符號不輸出至目標檔符號表,其他 .c 無法 extern 存取,避免命名衝突、實現封裝。
void counter() {
static int count = 0; // 僅初始化一次,位於 BSS/資料區
count++;
printf("called %d times\n", count);
}
int main() {
counter(); // 1
counter(); // 2
counter(); // 3
}
關鍵差異:
static 區域變數:程式啟動時配置於靜態區,**只初始化一次**,跨呼叫保留值,但**作用域仍限於函數內**。全域變數本身已有靜態儲存期,static 僅改變連結屬性 (內部連結)。
// C11 保證無競爭初始化
void init_once() {
static _Atomic int flag = 0;
if (atomic_load(&flag)) return;
// ... 複雜初始化 ...
atomic_store(&flag, 1);
}
static int (*callback)(int) = NULL; // 檔案內部可設定的回呼
void set_callback(int (*fn)(int)) { callback = fn; }
int invoke(int x) { return callback ? callback(x) : -1; }
static int a; int b; 在檔案頂層:a 內部連結,b 外部連結。static **不改變**區域變數作用域 (仍為區塊作用域),只改變儲存期。const static int x = 1;:const 修飾型別,static 修飾儲存類別,順序可互換。static 區域變數會共享同一記憶體,導致錯誤結果。| 場景 | 建議 |
|---|---|
| 檔案內部工具函數/變數 | 加 static 限制作用域,減少連結器符號汙染 |
| 需跨呼叫保留狀態的函數 | 使用 static 區域變數 (計數器、快取、單例) |
| 大型專案模組化 | 配合 static + 標頭檔 #ifndef 實現資訊隱藏 |
| 多執行緒環境 | 避免 static 區域變數共享狀態,改用 _Thread_local (C11) 或傳遞上下文結構體 |
| 嵌入式系統 | 善用 static 減少 RAM 碎片,將常態資料置於 .data/.bss |
static 指定內部連結。static、extern、_Thread_local、auto、register。