In C++, const
variables are implicitly hidden from other translation units. Is is possible to prevent开发者_Go百科 that?
Yes, prefix the definition with extern
eg.
extern const int x = 10;
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!
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).
精彩评论