Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "extern int &c;" working fine?

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?

like image 868
msc Avatar asked Nov 11 '17 12:11

msc


People also ask

What does extern int mean?

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.

What is the purpose of extern variable?

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.

What is the meaning of extern int in C?

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.

When should I use extern?

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.


2 Answers

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.

like image 158
immortal Avatar answered Oct 17 '22 13:10

immortal


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.

like image 21
Vittorio Romeo Avatar answered Oct 17 '22 13:10

Vittorio Romeo