c - c中修饰符static的使用

标签 c

我是初学者学习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文件。因此,您示例中的 nf 被认为是您的 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/

相关文章:

c++ - XCode 附加进程/分离进程(以编程方式分离调试器)

组合套接字发送的十六进制值

c - 如何让 gcc 对嵌入式系统和 void main(void) 感到满意

c - 如何访问作为指针传递给函数的结构中定义的指针变量?

c - 如何在 libwebsockets 回调中设置用户自定义指针?

C函数看不到全局变量

c - 事物被错误地读入数组

C - 凯撒密码 [将代码移至函数]

从用户区复制变量

c - 填充有什么好处?