一、全局变量
全局变量默认是静态的,通过extern关键字声明后可以在多个文件中使用。
具体可参考:C++变量的声明、定义和extern关键字
header.h
1 2 3 4 5 |
#pragma once extern int gCnt; int f1(); int f2(); |
source1.cpp
1 2 3 4 5 6 |
#include"header.h" int gCnt = 10; int f1() { return gCnt; } |
source2.cpp
1 2 3 4 5 |
#include"header.h" int f2() { return gCnt; } |
main.cpp
1 2 3 4 5 6 7 8 9 |
#include<iostream> #include"header.h" using namespace std; int main() { cout << f1() << endl; cout << f2() << endl; return 0; } |
source1.cpp
和source2.cpp
可共同使用全局变量gCnt
,程序将输出:
1 2 |
0 0 |
二、static
对于全局的static变量,它的作用域只在当前的文件,即使外部使用extern
关键字也是无法访问的。
修改source1.cpp
中的gCnt声明为:
1 |
static int gCnt = 10; |
编译不通过:
1 2 |
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
的定义:
1 |
int gCnt; |
添加后程序运行结果为:
1 2 |
10 0 |
两个文件的gCnt
不共通,所以f1()返回10
,f2()返回0
。
2022年6月28日 上午6:44 1F
为什么我的执行结果和你的不一样???
2022年8月19日 下午8:20 B1
@ 辅导费 可以发一下是哪一段代码