I have two .c files, one of them has the definition of x, and the other file is using x, as follows:
file1.c:
int x;
//other code...
main.c:
int main(void)
{
printf("%d", x);
}
Now, when I compile this code, I get the following compilation error message:
In function 'main':
error: 'x' undeclared (first use in this function)
So, if a global variable (in this case x
) is 'extern' by default, then why can't main.c
file see x
?
When I now go to main.c
and define x
, so that main.c
now looks like:
int x=9; //This line was added.
int main(void)
{
printf("%d",x);
}
And also initialize x in file1.c, the program doesn't compile and I get the following error message:
error: ld returned 1 exit status
So, if main.c
can't see x
that is in file1.c
, then this time what is the problem?
Is this a linking error?
Note that when I add
extern int x;
in main.c
, the problem disappears.