In C++, const
variables are implicitly hidden from other translation units. Is is possible to prevent that?

- 256,549
- 94
- 388
- 662
-
Prevent one having internal linkage, or prevent all of them from having internal linkage by default? – Steve Jessop Jan 14 '11 at 10:31
-
2@Steve: Only one. I don't want to change the language rules ;-) – fredoverflow Jan 14 '11 at 10:40
-
more fun about linkage of variables: http://stackoverflow.com/questions/3538807/linkage-of-various-const-static-variables – Johannes Schaub - litb Jan 14 '11 at 10:47
3 Answers
Use the extern
keyword:
extern const int x = 10;
This forces the variable to have external linkage.
For namespace-scope variables this is usually the default, and you'd use static
(or, better, an anonymous namespace) to force internal linkage.
I didn't actually know that namespace-scope const
variables have internal linkage by default until I read your question and tried it out, so thanks for that. Learn something new every day!

- 378,754
- 76
- 643
- 1,055
It can be achieved by means of the extern
keyword:
// a.cpp
extern const int x = 10; // definition
// b.cpp
extern const int x; // declaration
The effect this will have is that you will not need to recompile b
if the value of the constant changes in a
, but at the same time you loose the ability to use x
as a compile time constant inside b.cpp
(i.e. you will not be able to write int array[x];
).
If there isn't a very strong reason for this, I would rather have the constant defined in a header file and included in all translation units that require it;
// c.h
const int x = 10;
// a.cpp
#include "c.h"
// b.cpp
#include "c.h"
You will have to recompile all translation units that depend on the constant with each change, but you will be able to use it at compile time in all translation units. The limitation of this approach is that if you change the constant and only recompile some of the translation units, the value of the constant will be inconsistent (this is a violation of the ODR).

- 204,818
- 23
- 294
- 489
-
Yea, I'm not sure why you'd do that. Put a declaration (`extern const int x;`) in your header, sure, but why not leave the definition strictly in one TU? Precisely for the reasons you give, incidentally. :) – Lightness Races in Orbit Jan 14 '11 at 11:08