Using global variable in header file we can change value/use variable in another file(same value can access/modify in multiple files), then why extern can be used ? What is difference between global and extern ?
Below is the example that i have tried It doesnt make difference between extern and global variable in c.
Program compile and run successfully without any error.
t.h
int i;
t1.c
#include<stdio.h>
#include "t.h"
int main()
{
i=10;
printf("%s i = %d\n",__func__, i);
t2();
printf("%s i = %d\n",__func__, i);
i=200;
printf("%s i = %d\n",__func__, i);
t3();
printf("%s i = %d\n",__func__, i);
return 0;
}
t2.c
#include<stdio.h>
#include "t.h"
void t2()
{
printf("%s i=%d\n",__func__, i);
i = 100;
printf("%s i=%d\n",__func__, i);
}
t3.c
#include<stdio.h>
#include "t.h"
void t3()
{
printf("%s i=%d\n",__func__, i);
i = 300;
printf("%s i=%d\n",__func__, i);
}
Output :- gcc t1.c t2.c t3.c
main i = 10
t2 i=10
t2 i=100
main i = 100
main i = 200
t3 i=200
t3 i=300
main i = 300