本文将探讨程序级的全局变量在多文件中的使用。
1. const全局变量
const变量默认为文件级的局部变量:
//test.cpp
const int SIZE = 10;
以上定义的变量不能其它源文件中访问。
很多人定义const全局变量时,会用到类似如下的代码结构:
//common.h
const int SIZE = 10;
//func1.cpp
#include "common.h"
void func1 {
//use of SIZE
}
//func2.cpp
#include "common.h"
void func2 {
//use of SIZE
}
在以上的程序中,分别在三个文件中定义了相同名字的变量(若在func1和func2函数中添加一条语句std::cout << &SIZE << std::endl;就会发现,变量的地址是不同的)。因为const变量默认为文件级的局部变量,所以整个程序不会产生重定义SIZE的错误,程序运行正常,只是内存浪费了一点。如果要使程序只有一份SIZE变量,则需要加extern修饰符:
extern const int SIZE = 10;
以上的extern修饰符表示:SIZE变量可以被其他源文件引用。即SIZE是程序级的全局变量。
于是,修改之前的代码后,如下:
//common.h
extern const int SIZE;
//common.cpp
#include "common.h"
extern const int SIZE = 10;
//func1.cpp
#include "common.h"
void func1 {
//use of SIZE
}
//func2.cpp
#include "common.h"
void func2 {
//use of SIZE
}
以上common.h头文件中,对SIZE变量进行了声明,SIZE变量的定义则在common.cpp中。
References:
《C++ Primer中文版(第4版)》P49-50,P59-60
http://en.wikipedia.org/wiki/Static_variable