I have two files which are sharing the global variables.
In main.c
#include<stdio.h>
static int b;
extern int b;
main()
{
extern int a;
printf("a=%d &a:%p\n",a,&a);
printf("b=%d &b:%p\n",b,&b);
fn();
}
In fun.c
#include<stdio.h>
int b=25;
int a=10;
fn()
{
printf("in fna=%d &a:%p\n",a,&a);
printf("in fnb=%d &b:%p\n",b,&b);
}
If I compile both files. I'm not getting any compilation error. And its fine.The output is
a=10 &a:0x804a018
b=0 &b:0x804a024
in fna=10 &a:0x804a018
in fnb=25 &b:0x804a014
But, in main.c if I alter the lines extern int b
and static int b
like this
#include<stdio.h>
extern int b;
static int b;
main()
{
extern int a;
printf("a=%d &a:%p\n",a,&a);
printf("b=%d &b:%p\n",b,&b);
fn();
}
At compilation, I'm getting this error.
main.c:6:12: error: static declaration of ‘b’ follows non-static declaration
main.c:5:12: note: previous declaration of ‘b’ was here
Here the issue is with memory at which static and extern variables are stored. But I couldn't able to conclude the exact reason why is the compilation error at second time
Note: I'm using gcc compiler.