2

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

fredoverflow
  • 256,549
  • 94
  • 388
  • 662

3 Answers3

7

Yes, prefix the definition with extern eg.

extern const int x = 10;
Troubadour
  • 13,334
  • 2
  • 38
  • 57
3

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!

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
3

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).

David Rodríguez - dribeas
  • 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