在c++中何时使用extern

我正在阅读“用c++思考”,它刚刚引入了extern声明。例如:

extern int x;
extern float y;

我想我理解这个意思(没有定义的声明),但我想知道它什么时候被证明是有用的。

有人能举个例子吗?

507097 次浏览

当您在几个模块之间共享一个变量时,它很有用。在一个模块中定义它,在其他模块中使用extern。

例如:

在file1.cpp:

int global_int = 1;

在file2.cpp:

extern int global_int;
//in some function
cout << "global_int = " << global_int;

当你有全局变量时,这很有用。你在头文件中声明全局变量的存在,这样每个包含头文件的源文件都知道它,但你只需要“define”它曾经出现在你的源文件中。

为了澄清,使用extern int x;告诉编译器存在一个名为xint类型的对象。编译器不需要知道它在哪里,它只需要知道类型和名称,这样它就知道如何使用它。一旦所有源文件都编译完成,链接器将解析x的所有引用到它在已编译的源文件中找到的一个定义。为了让它工作,x变量的定义需要有所谓的“外部链接”,这基本上意味着它需要在函数之外(通常称为“文件作用域”)声明,并且没有static关键字。

标题:

#ifndef HEADER_H
#define HEADER_H


// any source file that includes this will be able to use "global_x"
extern int global_x;


void print_global_x();


#endif

源1:

#include "header.h"


// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;


int main()
{
//set global_x here:
global_x = 5;


print_global_x();
}

源2:

#include <iostream>
#include "header.h"


void print_global_x()
{
//print global_x here:
std::cout << global_x << std::endl;
}

这在需要全局变量时非常有用。在某个源文件中定义全局变量,并在头文件中将它们声明为extern,以便包含该头文件的任何文件都将看到相同的全局变量。

这都是关于链接

前面的答案提供了关于extern的很好的解释。

但我想补充一点。

你问了c++中的extern,而不是C中的extern,我不知道为什么没有答案提到c++中extern附带const的情况。

在c++中,const变量默认具有内部链接(不像C)。

因此,这种情况将导致连接错误:

来源1:

const int global = 255; //wrong way to make a definition of global const variable in C++

来源二:

extern const int global; //declaration

它应该是这样的:

来源1:

extern const int global = 255; //a definition of global const variable in C++

来源二:

extern const int global; //declaration