我是初学者学习c。我知道使用“static”一词会使 c 函数和变量在其声明的源文件中成为本地变量。但请考虑以下内容......
测试.h
static int n = 2;
static void f(){
printf("%d", n);
}
主.c
#include <stdio.h>
#include "test.h"
int main()
{
printf("%d", n);
f();
return 0;
}
我的预期结果是会抛出一条错误消息,因为函数 f 和变量 n 仅在 test.h 中是本地的?谢谢。
但相反,输出是
2
2
编辑: 如果它仅适用于编译单元,那是什么意思?以及如何按预期方式使用 static?
最佳答案
static
使您的函数/变量局部于编译单元,即当您编译单个 .c< 时读取的整套源代码
文件。
#include
.h
文件有点像将此头文件的内容复制/粘贴到您的.c
文件。因此,您示例中的 n
和 f
被认为是您的 main.c
编译单元的本地内容。
例子
模块.h
#ifndef MODULE_H
#define MODULE_H
int fnct(void);
#endif /* MODULE_H */
module.c
#include "module.h"
static
int
detail(void)
{
return 2;
}
int
fnct(void)
{
return 3+detail();
}
main.c
#include <stdio.h>
#include "module.h"
int
main(void)
{
printf("fnct() gives %d\n", fnct());
/* printf("detail() gives %d\n", detail()); */
/* detail cannot be called because:
. it was not declared
(rejected at compilation, or at least a warning)
. even if it were, it is static to the module.c compilation unit
(rejected at link)
*/
return 0;
}
构建(编译每个 .c
然后链接)
gcc -c module.c
gcc -c main.c
gcc -o prog module.o main.o
关于c - c中修饰符static的使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56849279/