什么是初始化extern const变量的正式方法?

时间:2013-06-17 03:04:14

标签: c++ initialization global-variables const

我正在使用.h文件将所有全局变量放在一个文件中,以确保所有文件都可以访问相同的值。但我有一个const int,我想知道我应该把它放在哪里?

·H:

#ifndef globalVar_H
#define globalVar_H


const int MAXCPU;
const int MAXPreBorder;

#endif

的.cpp:

int MAXCPU=12;
int MAXPreBorder=20;

我想我应该在.h文件中声明并在.cpp文件中初始化。但编译说:

error: non-type template argument of type 'int' is not an integral constant expression

如果我在.h文件中初始化。编译器不会抱怨..我想知道这是不是正确的方法?

·H:

#ifndef globalVar_H
#define globalVar_H


const int MAXCPU=12;
const int MAXPreBorder=20;

#endif

的.cpp:

//nothing?

2 个答案:

答案 0 :(得分:3)

const变量也是(默认情况下)static,因此每个.cpp文件都有一个唯一的变量,其中包含标题。

因此,您通常希望“就地”初始化它,因为在一个TU中定义的实例将与您在源文件中初始化的实例不同。

答案 1 :(得分:1)

globalVar.h:

#ifndef globalVar_H
#define globalVar_H


extern const int MAXCPU;
extern const int MAXPreBorder;

#endif

globalVar.cpp:

const int MAXCPU = 12;
const int MAXPreBorder = 20;
相关问题