如何在c语言中的多个源文件之间共享变量及其值?

我有两个名为file1.c和file2.c的源文件(.c)需要在它们之间共享一个变量,这样如果在一个源文件中变量已被更新,那么在访问此变量时,在另一个源文件中更改会被看到。

我所做的是创建另一个名为file3.c的源文件和名为file3.h的头文件(当然,它包含在file1.c file2.c和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更新并更新myvariable时,无法在file2.c中看到更改,因为在file2.c中调用get并打印myvariable然后打印0,仅在file2.c中调用update,然后看到更改。 似乎变量是共享的,但对于每个源文件,此变量有不同的变量值/不同的内存

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

在file1.c和file2.c中包含file3.h

我建议避免使用extern变量,因为代码混乱 – 使用全局重复每个文件中的externs。 通过将全局变量static绑定到某个文件范围通常更好。 然后使用interface函数来访问它。 在您的示例中,它将是:

 // in file3.h void update(int x); int get(void); // in file3.c: static int myVariable = 0; void update(int x){ myVariable = x; } int get(){ return myVariable; } // in other files - include file3.h and use // update() / get() to access static variable 

这是一个可能的解决方案。 这样做变量对整个应用程序来说不是全局的,只能使用访问函数读/写。 如果您有任何疑问,请告诉我。

文件: access.c access.h file2.c main.c
编译: gcc main.c file2.c access.c -o test
运行: ./test

文件:main.c

 #include  #include "access.h" int main( int argc, char *argv[] ) { int value; put( 1 ); printf("%d\n", get()); put( getValue() + 1 ); printf("%d\n", getValue()); return(0); } 

文件:access.c

 #include "access.h" static int variable = 0; int get( void ) { return(variable); } void put( int i ) { variable = i; return; } 

文件:file2.c

 #include  #include "access.h" int getValue( void ) { int i = get(); printf("getValue:: %d\n", i); put(++i); printf("after getValue:: %d\n", get()); return( i ); } 

文件:access.h

 extern int getValue( void ); extern int get( void ); extern void put( int i ); 

这是运行输出:

 [root@jrn SO]# ./test 1 getValue:: 1 after getValue:: 2 getValue:: 3 after getValue:: 4 4 

我希望这有帮助。