I am trying to implement a global variable that will be able to be used by different files and at the same time with std::array, but I get the following compiler error:
error: the value of ‘constants::HEIGHT’ is not usable in a constant expression
note: ‘constants::HEIGHT’ was not initialized with a constant expression
My code is split in the following files at the moment:
main.cpp
#include <iostream>
#include "classA.h"
#include "globals.h"
namespace constants {
extern const int WIDTH = 800;
extern const int HEIGHT = 600;
}
int main()
{
ClassA classA;
printf("Hello World");
std::cout << constants::WIDTH << " " << constants::HEIGHT << std::endl;
return 0;
}
classA.h
#include <array>
#include "globals.h"
class ClassA {
public:
std::array<int, constants::HEIGHT> m_arrayFixedRGBA;
ClassA();
};
classA.cpp
#include "classA.h"
ClassA::ClassA() {
}
globals.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace constants {
extern const int WIDTH;
extern const int HEIGHT;
}
#endif
I know that by removing extern
, declaring the values in globals.h
like this
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace constants {
const int WIDTH = 800;
const int HEIGHT = 600;
}
#endif
and removing the relevant lines in main.cpp
, then the program is able to compile.
While this is simple (and fine for smaller programs), every time globals.h
gets #included into a different code file, each of these variables is copied into the including code file. Therefore, if globals.h
gets included into 20 different code files, each of these variables is duplicated 20 times. Header guards won’t stop this from happening, as they only prevent a header from being included more than once into a single including file, not from being included one time into multiple different code files. This duplication of variables isn’t really that much of a problem (since constants aren’t likely to be huge), but changing a single constant value would also require recompiling every file that includes the constants header, which can lead to lengthy rebuild times for larger projects.
What could be a work-around for this scenario?