static 是 C 語言最「多面」的關鍵字:修飾局部變量改變**生命週期**,修飾全局變量/函數限制**鏈接可見性**。本文分場景徹底講透四大用法,附運行時內存模型與最佳實踐。
void counter() {
static int count = 0; // 僅初始化一次!
printf("%d ", ++count);
}
int main() {
counter(); // 1
counter(); // 2
counter(); // 3
}
auto)// file1.c static int g_private = 42; // 僅本文件可見 // file2.c extern int g_private; // 鏈接錯誤:找不到符號
static int x;)// utils.c
static void helper() { ... } // 僅本文件可調用
// main.c
void helper(); // 聲明無效,鏈接失敗
static void foo(),互不干擾#includestatic int g_static = 10; // 靜態全局 int func1() { static int local = 0; // 靜態局部 return ++local; } int func2() { g_static = 0; // 普通全局 (無 static) return ++g_static; } int main() { for (int i = 0; i < 10; i++) printf("%d, %d\n", func1(), func2()); return 0; }
輸出:
1, 1
2, 1
3, 1
...
10, 1
func1 靜態局部遞增,func2 每次重置全局為 0 再遞增 → 恆為 1。
auto 變量棧上,函數結束即釋放auto 運行期每次調用賦值auto 未初始化 → 不定值 (垃圾)static**static 變量/函數 (每個 .c 產生獨立副本,極易誤用)_Thread_local 或鎖保護