简体   繁体   English

为什么“extern int&c;”工作正常?

[英]Why does “extern int &c;” working fine?

In C++, reference variable must be initialized. 在C ++中,必须初始化引用变量。 int &a; 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说明符引用的错误?

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. extern关键字是编译器的一个指令,您现在声明一个符号,该符号将在链接期间从另一个目标文件中获取。 The initialization is EXPECTED to happen where the actual symbol is defined. 初始化是在实际符号定义的地方发生的。

If you have an ac file with 如果你有一个ac文件

int foo;
int &bar = foo;

And a bc file with 和一个bc文件

extern int &bar;

When you compile the file bc into bo the compiler will leave the symbol for bar empty. 当你将文件bc编译成bo时,编译器会将bar的符号留空。 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 当链接程序,链接器将需要找到出口标志bar在AO,然后将与替换博空白符号bar从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? 为什么编译器没有给出extern引用的错误?

Because extern int &c; 因为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. 它通知编译器c将在程序的其他地方定义。

The cppreference page on "storage class specifiers" explains the meaning of extern in this scenario. “存储类说明符”上cppreference页面解释了此场景中extern的含义。

The language specification explicitly says 语言规范明确说明

8.3.2 References 8.3.2参考文献
5 [...] The declaration of a reference shall contain an initializer (8.6.3) except when the declaration contains an explicit extern 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); 5 [...]引用的声明应包含初始值设定项(8.6.3),除非声明包含显式的extern说明符(7.1.1),是类定义中的类成员(9.2)声明,或者是声明参数或返回类型(8.3.5); see 3.1. 见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. 没有人禁止您将初始化程序包含在带有显式extern关键字的引用声明中。 However, as usual, it will turn a non-defining declaration into a definition . 但是,像往常一样,它会将非定义声明转换为定义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM