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

查看:183
本文介绍了何时在C ++中使用extern的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过用C ++思考。它只是引入了extern声明,例如

  extern int x; 
extern float y;

我想我有意义(声明没有定义),但我不知道什么时候有用。 / p>

有人可以提供一些例子吗?

解决方案

你有全局变量。您在标头中声明全局变量的存在,以便包含该标题的每个源文件都知道它,但您只需要定义<



要澄清,使用 extern int x; 告诉编译器类类型的对象 int 。它不是编译器的工作,知道它的存在,它只需要知道类型和名称,所以它知道如何使用它。一旦所有源文件都被编译,链接器将解析 x 的所有引用到在其中一个编译的源文件中找到的一个定义。为了工作, x 变量的定义需要具有所谓的外部链接,这基本上意味着它需要在一个函数之外声明



标题:



  #ifndef HEADER_H 
#define HEADER_H

//包含此内容的任何源文件将能够使用global_x
extern int global_x;

void print_global_x();

#endif



来源1:



  #includeheader.h

//需要定义
int global_x;

int main()
{
//设置global_x这里:
global_x = 5;

print_global_x();
}



源2:



  #include< iostream> 
#includeheader.h

void print_global_x()
{
//打印global_x这里:
std :: cout< global_x< std :: endl;
}


I'm readin' "Think in C++". It just introduced the extern declaration, e.g.

extern int x;
extern float y;

I guess I got the meaning (declaration without definition), but I wonder when it comes useful.

Can someone provide some example?

解决方案

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.

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.

header:

#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

source 1:

#include "header.h"

// it needs to be defined somewhere
int global_x;

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

    print_global_x();
}

source 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天全站免登陆