我遇到了一些在头文件中有一个大的静态函数的代码,我只是好奇它是不是可以做到这一点.例如,如果许多.c文件包含标题,为什么不直接定义非静态函数并将其链接?
关于何时/何时不将静态函数定义放在C中的头文件中的任何建议或经验法则,我们将不胜感激,
谢谢
我知道静态函数的名称只在声明它的文件(翻译单元)中可见.这使得封装成为可能.
但是静态函数通常在源文件中声明,因为如果你在头文件中执行它,你最终会得到它的多个实现(我认为这不是我的意图static).
例:
main.c中
#include "functions.h"
int main()
{
FunctionA();
FunctionB(); // Can't call regardless of "static".
return 0;
}
Run Code Online (Sandbox Code Playgroud)
functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
void FunctionA();
#endif /* FUNCTIONS_H */
Run Code Online (Sandbox Code Playgroud)
functions.c
#include "functions.h"
#include <stdio.h>
static void FunctionB(); // Same whether "static" is used or not.
void FunctionA()
{
printf("A");
}
void FunctionB()
{
printf("B");
}
Run Code Online (Sandbox Code Playgroud)
那么什么时候static有用?