【C】 static用法

 static用法

1. 在 C语言 中,static 关键字用于控制变量或函数的作用域和生命周期。当它修饰函数时,含义如下:

static int add(int a, int b) {
    return a + b;
}

上面的函数前加了 static,表示这是一个 静态函数(static function)。它的特点是:该函数的作用域仅限于当前源文件(.c 文件)内部,不能被其他文件访问。

 

 

2. 如果在 .h 头文件中定义了一个 static 函数,会发生什么。

static 修饰函数 → 内部链接(internal linkage)
👉 只能在**定义它的编译单元(.c 文件)**中使用。

⚠️ 编译单元(translation unit)指的是:
每个 .c 文件经过预处理(含入所有头文件)后形成的独立编译单元。

 

假设我们有头文件:

// util.h
static int add(int a, int b) {
    return a + b;
}

然后两个源文件都 #include 它:

// file1.c
#include "util.h"
void f1() {
    int x = add(1, 2);
}
// file2.c
#include "util.h"
void f2() {
    int y = add(3, 4);
}

 

当编译器处理 file1.c 时,会把 util.h 的内容直接拷贝进来。同理,file2.c 也会拷贝一份。所以实际上你生成了两个完全独立的函数副本:

file1.o: 定义了一个 static int add()
file2.o: 又定义了一个 static int add()

因为 static 函数是“文件私有”的,每个文件内部都有自己的一份拷贝,不会冲突,也不会共享。

posted @ 2025-11-03 20:37  苏格拉底的落泪  阅读(9)  评论(0)    收藏  举报