Reputation: 2799
I'm using a .h file to put all the global variables in one file to make sure all files can access the same value. But i have a const int, I wonder where should I inisilize it?
.h:
#ifndef globalVar_H
#define globalVar_H
const int MAXCPU;
const int MAXPreBorder;
#endif
.cpp:
int MAXCPU=12;
int MAXPreBorder=20;
I think I should declare in the .h file and initialize in the .cpp file. But the compiler said:
error: non-type template argument of type 'int' is not an integral constant expression
If I initialize in the .h file. the compiler would not complain.. I wonder if this is the right way?
.h:
#ifndef globalVar_H
#define globalVar_H
const int MAXCPU=12;
const int MAXPreBorder=20;
#endif
.cpp:
//nothing?
Upvotes: 2
Views: 2581
Reputation: 490358
A const
variable is also (by default) static
, so you have a unique one for each .cpp
file in which the header is included.
As such, you normally want to initialize it "in place", since the instance defined in one TU won't be the same as the instance you initialized in your source file.
Upvotes: 3
Reputation: 20858
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;
Upvotes: 2