Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Putting a const in a header

Tags:

c++

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?

like image 719
johnbakers Avatar asked Jan 20 '13 22:01

johnbakers


1 Answers

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.

like image 182
Kerrek SB Avatar answered Sep 22 '22 02:09

Kerrek SB