I have tried the following code:
File1.c:
int x;
File2.c:
extern char x;
main()
{
x=10;
....
....
}
and compiled as
$gcc File1.c File2.c
and I didn't get any error but I was expecting one.
I have tried the following code:
File1.c:
int x;
File2.c:
extern char x;
main()
{
x=10;
....
....
}
and compiled as
$gcc File1.c File2.c
and I didn't get any error but I was expecting one.
In File.c
, you promise to the compiler that x
is of type char
. Since every translation unit is compiled separately, the compiler has no way of verifying this, and takes your word for it. And the linker doesn't do any type checking. You end up with an invalid program that builds with no errors.
This is why you should use header files. If File1.c
and File2.c
both got an extern
declaration of x
from the same header, then you would get an error when compiling File1.c
(because the definition doesn't match the declaration). [Hat tip @SteveJessop]