[英]How to get the value of global static variables having same name in 2 separate files in C program
I'm trying to execute a program in C.我正在尝试执行 C 中的程序。 While executing I'm getting the same value for global static variables( static int data ) with the same name declared in 2 separate files program1.c and program2.c where the main() function is in program1.c The actual answer should be apple = 2 and orange = 3 but the static int data variable is getting overridden by oranges_set(3) function call.
While executing I'm getting the same value for global static variables( static int data ) with the same name declared in 2 separate files program1.c and program2.c where the main() function is in program1.c The actual answer should be apple = 2和orange = 3但static int 数据变量被oranges_set(3) function 调用覆盖。 Could anyone please let me know what could be the issue?
谁能让我知道可能是什么问题? Thanks in advance.
提前致谢。
program1.c
#include <stdio.h>
#include "program2.c"
void apples_set(int value);
int apples_get();
static int data;
void oranges_set(int value)
{
data = value;
}
int oranges_get()
{
printf("Value of oranges = %d \n",data);
return data;
}
int main(){
apples_set(2);
oranges_set(3);
printf("Apple = %d and Orange = %d",apples_get(),oranges_get());
return 0;
}
======================================================== ==================================================== ======
program2.c程序2.c
static int data;
void apples_set(int value)
{
data = value;
}
int apples_get()
{
printf("Value of apples = %d \n",data);
return data;
}
These are not separate files, because you include the one in the other.这些不是单独的文件,因为您将一个包含在另一个文件中。 This is equivalent to copying the entire content of
program2.c
and pasting it place of the #include "program2.c"
line in program1.c
.这相当于复制
program2.c
的全部内容并将其粘贴到 program1.c 中#include "program2.c"
program1.c
的位置。
For this to work correctly, you need to compile the files as separate object files and then link those together.为此,您需要将文件编译为单独的 object 文件,然后将它们链接在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.