全局变量是C++非常基础的知识,但是使用时的bug偶尔会有。本人总结了以下全局变量的使用方法,主要以extern为例:
有以下4个文件:
tmc2.cpp(包含main函数,全局变量定义)
tmc2.h(包含全局变量声明)
predict.cpp(使用全局变量)
predict.h
tmc2.h:
#ifndef TMC2_h
#define TMC2_h
extern int ext_para;
tmc2.cpp
#include "TMC2.h"
#include "predict.h"
int ext_para=0;
int main()
{
ext_para=5;
predict();
}
predict.h
#ifndef predict_h
#define predict_h
void predict();
predict.cpp
#include "TMC2.h"
#include "predict.h"
#include <iostream>
void predict()
{
std::cout<<ext_para<<std::endl;
}
最终输出结果为5
注意事项:
- 全局变量的 声明 与 初次定义 必须分别在两个同名的头文件(.h) 与源文件(.cpp) 中
- 初次定义全局变量必须在函数外定义,多文件编程最好是在main函数运行前就执行定义,不然后续在其他文件使用时会无法读取该变量。