From everything I am reading and testing, there is no way (without a preprocessor macro) to define a constant in a shared header and ensure that each TU is not creating its own storage for that constant.
I can do this:
const int maxtt=888888;
Which is the same exactly as:
static const int maxtt=888888;
And if this header is shared, it will work but each TU gets its own copy of maxtt
. I could also do this, to prevent that:
extern const int maxtt;
But then I cannot define maxtt
here; that must be done in a CPP to avoid linker error.
Is my understanding correct?
Since the variable is constant, the fact that each TU gets its own copy is usually irrelevant.
In C++, constants at namespace scope are implicitly static
for this reason. Often this allows for better code than if you only had a single instance with external linkage, since (if the variable is actually a constant expression) the constant can often be folded right into the usage site and doesn't need to be stored at all.
So unless you really need to take the address of the constant, or something like that, you should stick with the static version. (And as you already observed, you can force external linkage by adding extern
.) Another reason may be that you're initializing dynamically and only want one call to the initializer:
// header:
extern int const n;
// one implementation:
int const n = init_function_with_side_effects();
The static construction (int const n = init();
in the header) would cause the function to be called once in every TU.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With