C++中的extern

这篇文章解释的简单明了:

https://stackoverflow.com/questions/10422034/when-to-use-extern-in-c

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;

}

 

转载于:https://www.cnblogs.com/time-is-life/p/8875650.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值