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 ac file with
int foo;
int &bar = foo;
And a bc file with
extern int &bar;
When you compile the file bc into bo the compiler will leave the symbol for bar
empty. When linking the program, the linker will need to find the exported symbol bar
in ao and will then replace the blank symbol in bo with the bar
from ao
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.
The language specification explicitly says
8.3.2 References
5 [...] The declaration of a reference shall contain an initializer (8.6.3) except when the declaration contains an explicitextern
specifier (7.1.1), is a class member (9.2) declaration within a class definition, or is the declaration of a parameter or a return type (8.3.5); see 3.1.
Your situation is directly covered by this quote. In other words, references are not excepted from the general declaration-definition rule. You can create a non-defining declaration for a reference defined (and initialized) elsewhere.
Nobody prohibits you from including an initializer into a reference declaration with an explicit extern
keyword. However, as usual, it will turn a non-defining declaration into a definition .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.