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.
Initialization — if a global variable is declared in more than one source file in a library, it should be initialized in only one place or you will get a compiler error. Static — use the static keyword to make a global variable visible only to functions within the same source file whenever possible.
An introduction to C Global Variablesj is not available anywhere outside the main function. A global variable can be accessed by any function in the program. Access is not limited to reading the value: the variable can be updated by any function.
Use of the Global Variable in CThe global variables get defined outside any function- usually at the very top of a program. After this, the variables hold their actual values throughout the lifetime of that program, and one can access them inside any function that gets defined for that program.
The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With