以下是一个简单的示例,展示了 static 函数的用法:
file1.c
#include <stdio.h>
// 定义一个静态函数,只能在 file1.c 中使用
static void helper() {
printf("This is a static function in file1.c\n");
}
// 非静态函数,可以被其他文件调用
void publicFunc() {
printf("Calling helper from file1.c:\n");
helper(); // 可以调用 static 函数
}
file2.c
#include <stdio.h>
// 尝试调用 file1.c 中的 helper 函数
void tryToCallHelper() {
// helper(); // 错误:helper 不可见,因为它是 file1.c 中的 static 函数
printf("Cannot call helper() from file2.c\n");
}
int main() {
publicFunc(); // 可以调用 file1.c 中的非静态函数
tryToCallHelper();
return 0;
}
作用域:static 函数的作用域仅限于定义它的文件内部。
链接属性:静态函数具有内部链接属性,不会与其他文件中的同名函数冲突。
用途:适合用于实现文件内部的辅助功能,避免暴露给外部文件。
通过使用 static 修饰函数,可以提高代码的封装性和可维护性,同时避免命名冲突。
|