一、全局变量

全局变量默认是静态的,通过extern关键字声明后可以在多个文件中使用。

具体可参考:C++变量的声明、定义和extern关键字

header.h

#pragma once
extern int gCnt;

int f1();
int f2();

source1.cpp

#include"header.h"

int gCnt = 10;
int f1() {
    return gCnt;
}

source2.cpp

#include"header.h"

int f2() {
    return gCnt;
}

main.cpp

#include<iostream>
#include"header.h"
using namespace std;

int main() {
    cout << f1() << endl;
    cout << f2() << endl;
    return 0;
}

source1.cppsource2.cpp可共同使用全局变量gCnt,程序将输出:

0
0

二、static

对于全局的static变量,它的作用域只在当前的文件,即使外部使用extern关键字也是无法访问的。

修改source1.cpp中的gCnt声明为:

static int gCnt = 10;

编译不通过:

1>source2.obj : error LNK2001: 无法解析的外部符号 "int gCnt" (?gCnt@@3HA)
1>F:\code\cpp\2-cpp_primer\Debug\5-extern.exe : fatal error LNK1120: 1 个无法解析的外部命令

因为source2.cpp中无法访问source1.cpp中的gCnt,导致gCnt未定义,需要在source2.cpp中添加gCnt的定义:

int gCnt;

添加后程序运行结果为:

10
0

两个文件的gCnt不共通,所以f1()返回10,f2()返回0

最后修改:2018 年 03 月 15 日
如果觉得我的文章对你有用,请随意赞赏