我正在读“用c++思考”,它刚刚引入了extern声明。例如:
extern int x;
extern float y;
我想我理解这个意思(没有定义的声明),但我想知道它什么时候被证明是有用的。
有人能举个例子吗?
我正在读“用c++思考”,它刚刚引入了extern声明。例如:
extern int x;
extern float y;
我想我理解这个意思(没有定义的声明),但我想知道它什么时候被证明是有用的。
有人能举个例子吗?
当您在几个模块之间共享一个变量时,它很有用。在一个模块中定义它,在其他模块中使用extern。
例如:
在file1.cpp:
int global_int = 1;
在file2.cpp:
extern int global_int;
//in some function
cout << "global_int = " << global_int;
当你有全局变量时,这很有用。在头文件中声明全局变量的存在,这样每个包含头文件的源文件都知道它,但您只需要在一个源文件中“定义”它一次。
To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static keyword.
标题:
#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提供了很好的解释。
但我想补充一点。
你问的是c++中的extern,而不是C,我不知道为什么没有答案提到在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