- The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else.
- The extern declaration does not allocate storage for variables.
- Used to resolve the scope of global symbol
- Eg : Example Using extern in same file
main() { extern int x; //Tells compiler that it is defined somewhere else printf("%d",x); } int x=10; //Global variable x
Contents
Extern Variable Initializer
Extern as global variable initializer
- The extern keyword variable can be initialize when its global
Example : External variable always initialize (Zero) ‘0’
#include "stdio.h" extern int a; main(){ printf("a=%d",a); return 0; } int a; /* Output : a=0 */
Example : variable initialize in global variable
#include "stdio.h" extern int a; main(){ printf("a=%d",a); return 0; } int a =5; /* Output : a=5 */
Example :
#include <stdio.h> extern int a; int main() { void fun(); printf("\n a=%d",a); fun(); return 0; } int a=7; void fun() { printf("\n in fun a=%d",a); } /* Output : a=7 in fun a=7 */
Example : variable initialize in global variable
#include <stdio.h> extern int a=5; int main() { printf("%d",a); return 0; } /* Output : 5*/ /* Explanation pritf function print a value as 5. */
Example : variable initialize in global variable
#include <stdio.h> extern int a=5; int main() { void fun(); printf("\n a=%d",a); fun(); return 0; } int a; void fun() { printf("\n in fun a=%d",a); } /* Output : a=5 in fun a=5 */
Example : Error while running Linker
#include <stdio.h> extern int a; int main() { printf("\na=%d",a); return 0; } /* Output : // Error */ /* Error[e46]: Undefined external "a" referred in main Error while running Linker */
Extern as local variable initializer
- The extern keyword variable can not be initialize when its local or inside the function. (an initializer is not allowed on a local declaration of an extern variable)
EXample : an initializer is not allowed on a local declaration of an extern variable
#include <stdio.h> int main() { extern int a=5; printf("%d",a); return 0; } /* Output */ // Error[Pe2442]: an initializer is not allowed on a local declaration of an extern variable main.c