C语言中static变量的使用时机及内部连接特性详解
何时使用 static 作为变量的前缀?

如果使用静态说明符,标识符的第一个外部声明将导致标识符具有内部链接。内部链接标识符仅在当前.c源文件(translation unit,翻译单元)中可见,即仅在当前.c源文件中可见,而其他源文件则不可见。
如果声明的全局变量只在当前.c文件(翻译单元,翻译单元)中使用,不会在其他.c文件中使用,那么在.c而不是.h文件中将其声明为static; if 声明的全局变量将在其他.c文件中使用,因此将其声明为extern并将其放置在.h文件中。除 extern 外部变量外,不要在头文件中声明任何变量。否则,当在源文件中扩展头文件时,可能会出现多个变量声明。不要在头文件中定义变量。
参考堆栈溢出:
何时使用 static 作为函数的前缀?
如果声明的全局函数只在当前.c文件中使用,不想被外部访问,则应声明为静态类型。
C语言函数定义默认是全局的,声明为static的函数只在当前.c文件中可见,在其他.c文件中不可见;可以在其他 .c 文件中重新定义同名函数。
例子:
静态_fun.h
#pragma once
#include
static void static_fun();
void fun();
void printfun();
静态函数.c
#include "static_fun.h"
static int static_variable = 1;
static void static_fun() {
printf("Static fun call\n");
}
void fun() {
printf("Global fun call\n");
static_fun();
}
void printfun() {
printf("static variable is: %d\n", static_variable);
}
主程序
#include "static_fun.h"
int main()
{
// static function/variable call test
static_fun(); // error: static function decleared but not defined
fun(); // OK: extern function
printf("Static variable: %d\n", static_variable); // error: static_variable not defined
printfun(); // OK: access static variable by extern function
return 0;
}
static_fun()仅在static_fun.c中可见,因此对static_fun()的调用; main.c中被视为语句,但未找到函数定义;
printf static_variable的静态变量仅在static_fun.c中可见,因此该变量是未定义的;
静态变量或函数可以通过外部函数间接访问。
static关键字的这一特性在C语言中经常被用来设计和实现ADT(抽象数据类型),例如链表、树等抽象数据结构。静态声明的函数和变量仅在 ADT 内部可见,外部无法访问。
void func() {
static int val = 1;
++val;
printf("static value: %d\n", val);
}
int main()
{
func();
func();
return 0;
}
static value: 2
static value: 3
当包含 static 的函数被调用两次时,第二次定义不会生效,并且 static 变量不会重新初始化。当程序执行到静态变量时,它的值仍然是最后的结果。