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?
extern int i; declares that there is a variable named i of type int, defined somewhere in the program. extern int j = 0; defines a variable j with external linkage; the extern keyword is redundant here.
The extern keyword means "declare without defining". In other words, it is a way to explicitly declare a variable, or to force a declaration without a definition. It is also possible to explicitly define a variable, i.e. to force a definition. It is done by assigning an initialization value to a variable.
extern "C" specifies that the function is defined elsewhere and uses the C-language calling convention. The extern "C" modifier may also be applied to multiple function declarations in a block. In a template declaration, extern specifies that the template has already been instantiated elsewhere.
The “extern” keyword is used to declare and define the external variables. The keyword [ extern “C” ] is used to declare functions in C++ which is implemented and compiled in C language. It uses C libraries in C++ language.
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.
Why Compiler doesn't give an error for
extern
reference?
Because extern int &c;
is not a definition, but merely a declaration. It's informing the compiler that c
will be defined somewhere else in the program.
The cppreference page on "storage class specifiers" explains the meaning of extern
in this scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With