博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++中的extern
阅读量:6454 次
发布时间:2019-06-23

本文共 1345 字,大约阅读时间需要 4 分钟。

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

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;

}

 

转载地址:http://ukfzo.baihongyu.com/

你可能感兴趣的文章
关于java Integer大小比较的问题
查看>>
C++创建学生类练习
查看>>
C# 如何生成CHM帮助文件
查看>>
hdu1007 平面最近点对(暴力+双线程优化)
查看>>
栈和队列
查看>>
用VS2012或VS2013在win7下编写的程序在XP下运行就出现“不是有效的win32应用程序...
查看>>
重载运算符-operator
查看>>
次小生成树 - 堆优化
查看>>
用户管理 之 Linux 用户(user)和用户组(group)管理概述
查看>>
javascript 闭包
查看>>
log4j.properties 配置问题。
查看>>
Java高并发,解决思路
查看>>
第四次
查看>>
C# 委托
查看>>
Android中Context详解和获取SharedPreference
查看>>
(转载)EF 使用code first模式创建数据库和 填充种子数据
查看>>
[BZOJ1503]郁闷的出纳员(Splay)
查看>>
iOS 各种传值方式
查看>>
C程序设计学习笔记(完结)
查看>>
Django基础
查看>>