I want to define a constant in C++ to be visible in several source files. I can imagine the following ways to define it in a header file:
#define GLOBAL_
To answer your second question:
(2) is illegal because it violates the One Definition Rule. It defines GLOBAL_CONST_VAR
in every file where it's included, i.e. more than once.
(5) is legal because it's not subject to the One Definition Rule. Each GLOBAL_CONST_VAR
is a separate definition, local to that file where it's included. All those definitions share the same name and value of course, but their addresses could differ.
If you use C++11 or later, try using compile-time constants:
constexpr int GLOBAL_CONST_VAR{ 0xff };
(5) says exactly what you want to say. Plus it lets the compiler optimize it away most of the time. (6) on the other hand won't let the compiler ever optimize it away because the compiler doesn't know if you'll change it eventually or not.
If it's going to be a constant then you should mark it as a constant - that's why 2 is bad in my opinion.
The compiler can use the const nature of the value to expand some of the maths, and indeed other operations that use the value.
The choice between 5 and 6 - hmm; 5 just feels better to me.
In 6) the value is unnecessarily detached from it's declaration.
I typically would have one or more of these headers that only defines constants etc within them, and then no other 'clever' stuff - nice lightweight headers that can easily be included anywhere.