gpt4 book ai didi

c - 如何跨多个文件使用静态 C 变量?

转载 作者:太空狗 更新时间:2023-10-29 17:15:37 25 4
gpt4 key购买 nike

我有两个 C 文件 1.c 和 2.c

2.c

#include<stdio.h>

static int i;

int func1(){
i = 5;
printf("\nfile2 : %d\n",i);
return 0;
}

1.c

#include<stdio.h>

int i;

int main()
{
func1();
printf("\nFile1: %d\n",i);
return 0;
}

我用“gcc 1.c 2.c -o st”编译了这两个文件输出如下

file2 : 5

File2: 0

我期待的输出如下

file2 : 5

File2: 5

我想访问两个文件中的同一个变量“i”。我该怎么做?

最佳答案

选择一个将存储变量的文件。不要使用 staticstatic 的全部要点是保持变量私有(private)且不可被其他模块访问。

在所有其他文件中,使用 extern 关键字来引用变量:

extern int i;

关于c - 如何跨多个文件使用静态 C 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12728426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com