I have two C files 1.c and 2.c
#include<stdio.h>
static int i;
int func1(){
   i = 5;
   printf("\nfile2 : %d\n",i);
   return 0;
}
#include<stdio.h>
int i;
int main()
{
   func1();
   printf("\nFile1: %d\n",i);
   return 0;
}
I compiled both the files with "gcc 1.c 2.c -o st" The output is as follows
file2 : 5
File2: 0
I was expecting output as follows
file2 : 5
File2: 5
I want to access the same variable "i" in both the files. How can I do it?
A global variable is accessible to all functions in every source file where it is declared. To avoid problems: Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error.
No. It is not possible. Each process is in a separate address space.
Static variables can be assigned as many times as you wish. static int count = 0; is initialization and that happens only once, no matter how many times you call demo .
Static Members Only one copy of a static member exists, regardless of how many instances of the class are created.
Choose one file which will store the variable. Do not use static. The whole point of static is to keep the variable private and untouchable by other modules.
In all other files, use the extern keyword to reference the variable: 
extern int i;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With