How do I share a global variable between c files?

peter_perl picture peter_perl · Jul 22, 2011 · Viewed 105.4k times · Source

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.

Answer

Rocky Pulley picture Rocky Pulley · Jul 22, 2011

file 1:

int x = 50;

file 2:

extern int x;

printf("%d", x);