C语言 如何在 c 文件之间共享全局变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6792930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:11:46  来源:igfitidea点击:

How do I share a global variable between c files?

cextern

提问by peter_perl

If i define a global variable in a .cfile, how can i use the value of the same variable in another .cfile?

如果我在一个.c文件中定义了一个全局变量,我如何在另一个.c文件中使用同一个变量的值?

file1.c

文件1.c

#include<stdio.h>

int i=10;

int main()
{
printf("%d",i);
return 0;
}

file2.c

文件2.c

#include<stdio.h>

int main()
{
//some data regarding i
printf("%d",i);
return 0;
}

How can the second file use the value of ifrom the first file here.

第二个文件如何在i这里使用第一个文件中的值。

回答by Triton Man

file 1:

文件1:

int x = 50;

file 2:

文件2:

extern int x;

printf("%d", x);

回答by mdm

Use the externkeyword to declare the variable in the other .cfile. E.g.:

使用extern关键字在另一个.c文件中声明变量。例如:

extern int counter;

means that the actual storage is located in another file. It can be used for both variables and function prototypes.

意味着实际存储位于另一个文件中。它可以用于变量和函数原型。

回答by Murali VP

using extern <variable type> <variable name>in a header or another C file.

使用extern <variable type> <variable name>在报头或其它C文件。

回答by Asha

In the second .cfile use externkeyword with the same variable name.

在第二个.c文件中使用extern具有相同变量名的关键字。

回答by ami

Do same as you did in file1.c In file2.c:

像你在 file1.c 中所做的一样在 file2.c 中:

#include <stdio.h> 

extern int i;  /*This declare that i is an int variable which is defined in some other file*/

int main(void)
{
/* your code*/

If you use int i; in file2.c under main() then i will be treated as local auto variable not the same as defined in file1.c

如果你使用 int i; 在 main() 下的 file2.c 中,我将被视为与 file1.c 中定义的不同的局部自动变量

回答by Kiran Padwal

Use extern keyword in another .c file.

在另一个 .c 文件中使用 extern 关键字。

回答by bharaniprakash tumu

If you want to use global variable i of file1.c in file2.c, then below are the points to remember:

如果你想在 file2.c 中使用 file1.c 的全局变量 i,那么下面是要记住的要点:

  1. main function shouldn't be there in file2.c
  2. now global variable i can be shared with file2.c by two ways:
    a) by declaring with extern keyword in file2.c i.e extern int i;
    b) by defining the variable i in a header file and including that header file in file2.c.
  1. file2.c 中不应该有 main 函数
  2. 现在全局变量 i 可以通过两种方式与 file2.c 共享:
    a) 通过在 file2.c 中使用 extern 关键字声明,即 extern int i;
    b) 通过在头文件中定义变量 i 并将该头文件包含在 file2.c 中。