如何在c语言中的多个源文件之间共享一个变量及其值? [英] how to share a variable and its value between many source file in c language?

查看:1334
本文介绍了如何在c语言中的多个源文件之间共享一个变量及其值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个源文件(.c),名为file1.c和file2.c,它们需要在它们之间共享一个变量
,这样如果在一个源文件中该变量已更新,那么在另一个源文件中文件访问这个变量时会发生变化。

i have 2 source files (.c) named file1.c and file2.c which need to share between them a variable, so that if in one source file the variable is been updated then in the other sourced file when accessing this variable the change will be seen.

我做的是创建另一个名为file3.c的源文件和名为file3.h的头文件(当然, ,已包含在file1.c file2.c和file3.c中)

what i did is create another source file called file3.c and header file called file3.h (which, of course, is been included in file1.c file2.c and in file3.c)

in file3.c:

int myvariable = 0;

void update(){//updating the variable

    myvariable++;

}

int get(){//getting the variable

    return myvariable;

}

in file3.h:

extern int myvariable;

void update(void);

int get(void);

in file1.c:
.
.
.
printf("myvariable = %d",get());//print 0
update();
printf("myvariable = %d",get());//print 1
.
.
.

in file2.c:
.
.
.
printf("myvariable = %d",get());//print 0 but should print 1
.
.
.

但问题出在 file1.c update被调用并且myvariable被更新
file2.c 中看不到变化,因为在file2.c中调用get时,
myvariable是然后打印0,只有在file2.c更新被调用时,才会看到更改。
它看起来像变量是共享的,但是对于每个源文件,这个变量都有一个不同的变量值/不同的内存

but the problem is when in file1.c update is invoked and myvariable is updated the change cannot be seen in file2.c because in file2.c when get is invoked and myvariable is printed then 0 is been printed, only if in file2.c update is invoked then the change is been seen. it seems like the variable is shared but for each source file there is a different variable value/different memory for this variable

推荐答案

当您需要变量时,您可以在其他文件中将该变量声明为 extern 。 。

You can declare the variable as extern in the others file when you need the variable ...

这篇关于如何在c语言中的多个源文件之间共享一个变量及其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆