何时在 C++ 中使用 extern [英] When to use extern in C++

查看:45
本文介绍了何时在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆