Reputation: 61
When a global variable with the same name is defined across files, only one instance of the variable is actually defined in the memory. For example int temp is defined in a.c, b.c and main.c, when I check the address of the variables, they are same across all the files.
Now the variables are getting extended with out using the specifier extern, so what is the use of the extern?
file a.c
int temp;
a()
{
temp = 10;
printf("the value of temp in a.c is %d\n",temp);
}
file b.c
int temp;
b()
{
temp = 20;
printf("the value of temp in b.c is %d\n",temp);
}
file main.c
int temp;
main()
{
temp = 30;
a();
b();
printf("the value of temp in main.c is %d\n",temp);
}
o/p is
the value of temp in a.c is 10
the value of temp in b.c is 20
the value of temp in main.c is 20.
In the above case the value of temp in main.c is also 20 because it changed in b.c, and the latest value is getting reflected. Why is the variable temp getting extended with out creating 3 different variables?
Upvotes: 2
Views: 177
Reputation: 753990
You're accidentally exploiting a common extension to Standard C, described in Annex J.5.11 Multiple External Definitions.
There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2).
This is also sometimes called the 'common model' of variable handling, based on Fortran COMMON blocks. See How do I use extern
to share variables between source files in C? for more information. You don't need to read it all at the moment, though.
Your code is not strictly conforming to the standard. However, you will get away with it on many (but not all) systems. (C++ has a stronger rule called the ODR — One Definition Rule. You can think of the C rule as ODR-lite; but your code is violating even ODR-lite.)
Upvotes: 4