Reputation: 7841
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?
Upvotes: 9
Views: 28399
Reputation:
Its not recommended, but we can achieve it using pointers with extern storage class.
In 2.c
static int i;
int *globalvar = &i;
In 1.c
extern int *globalvar;
Upvotes: 1
Reputation: 213306
There is never a reason to access a static variable in another file. You don't seem to know why you are using the static keyword. There are two ways to declare variables at file scope (outside functions).
Global variable
int i;
Advantages:
Disadvantages:
Local/private variable
static int i;
Advantages:
Disadvantages:
My personal opinion is that there is never a reason to use global variables nor the extern keyword. I have been programming for 15+ years and never needed to use either. I have programmed everything from realtime embedded systems to Windows GUI fluff apps and I have never needed to use global variables in any form of application. Furthermore, they are banned in pretty much every single known C coding standard.
Upvotes: 6
Reputation: 838
static
variables can only be accessed within a single translation unit, which means that only code in the file that it is defined in can see it. The Wikipedia Article has a nice explanation. In this situation, to share the variable across multiple files you would use extern
.
Upvotes: 1
Reputation: 45598
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;
Upvotes: 15