If i define a global variable in a .c
file, how can i use the value of the same variable in another .c
file?
file1.c
#include<stdio.h>
int i=10;
int main()
{
printf("%d",i);
return 0;
}
file2.c
#include<stdio.h>
int main()
{
//some data regarding i
printf("%d",i);
return 0;
}
How can the second file use the value of i
from the first file here.
using extern <variable type> <variable name>
in a header or another C file.
Use extern keyword in another .c file.
In the second .c
file use extern
keyword with the same variable name.
Use the extern
keyword to declare the variable in the other .c
file. E.g.:
extern int counter;
means that the actual storage is located in another file. It can be used for both variables and function prototypes.
If you want to use global variable i of file1.c in file2.c, then below are the points to remember:
Do same as you did in file1.c In file2.c:
#include <stdio.h>
extern int i; /*This declare that i is an int variable which is defined in some other file*/
int main(void)
{
/* your code*/
If you use int i; in file2.c under main() then i will be treated as local auto variable not the same as defined in file1.c
Source: Stackoverflow.com