一、全局变量
全局变量默认是静态的,通过 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
。
1F
为什么我的执行结果和你的不一样???
B1
@ 辅导费 可以发一下是哪一段代码