In this code:
#include<stdio.h>
int var=100;
int main()
{
extern int var; //Declaration not Definition
printf("%d\n",var);
return 0;
}
100 is printed which is nothing out of the normal, but when declaration is removed from the main(), even then the global definition is being used. How is that happening? This has been taken from K&R which says:
The (global) variable must also be declared in each function that wants to access it.
There is no need to include the extern keyword for variables which are declared in the same file or module. The global variable is visible to main
since it has global scope (i.e. it is visible to all functions within the file/module).
To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files.