The extern keyword is used to tell the compiler that a data object is declared in a different *.cpp or *.c file. So there wont be any new memory is allocated for these variables. Check the below example and understand the working.
//file1.cpp #include <iostream.h> int x; extern void func2(); void func1(void) { x = x + 100; cout<<"x in func1 = "<< x << endl; } int main(void) { x = 10; cout<<"x in main function = "<< x << endl; func1(); // calls func1 func2(); // calls func2 from file2 } |
//file2.cpp #include <iostream.h> extern int x; void func2(void) { x = x + 300; cout<<"x in file2 = "<< x << endl; } |
Output:
x in main function = 10
x in func1 = 110
x in file2 = 410