In C++, reference variable must be initialized. int &a; // Error
static int &b; // Error
But
extern int &c; // No error
Why Compiler doesn't give an error for extern
specifier reference?
The extern
keyword is a directive for the compiler that you are now declaring a symbol that will be filled in during linking, taken from another object file.
The initialization is EXPECTED to happen where the actual symbol is defined.
If you have an a.c file with
int foo;
int &bar = foo;
And a b.c file with
extern int &bar;
When you compile the file b.c into b.o the compiler will leave the symbol for bar
empty. When linking the program, the linker will need to find the exported symbol bar
in a.o and will then replace the blank symbol in b.o with the bar
from a.o
If the linker can't find the required symbol anywhere in the linked object files - a Linker error (not compiler error) will be issued.