When to use extern in C++(何时在 C++ 中使用 extern)
问题描述
我正在阅读Think in C++",它刚刚引入了 extern
声明.例如:
I'm reading "Think in C++" and it just introduced the extern
declaration. For example:
extern int x;
extern float y;
我想我明白意思(没有定义的声明),但我想知道它什么时候证明有用.
I think I understand the meaning (declaration without definition), but I wonder when it proves useful.
谁能举个例子?
推荐答案
这在您拥有全局变量时很有用.你在头文件中声明全局变量的存在,这样每个包含头文件的源文件都知道它,但你只需要定义"它在您的源文件之一中出现一次.
This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.
澄清一下,使用extern int x;
告诉编译器int
类型的对象x
存在于某处.知道它在哪里存在不是编译器的工作,它只需要知道类型和名称,以便知道如何使用它.编译完所有源文件后,链接器会将 x
的所有引用解析为它在已编译源文件之一中找到的一个定义.为了使其工作,x
变量的定义需要具有所谓的外部链接",这基本上意味着它需要在函数之外声明(通常称为外部链接")文件范围")并且没有 static
关键字.
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;
}
这篇关于何时在 C++ 中使用 extern的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:何时在 C++ 中使用 extern
基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01