4

As I know there are two ways to declare a constant variable visible only in one file:

  1. Declare static const int VARIABLE = 1
  2. Declare it in a unnamed namespace:
namespace { const int VARIABLE = 1; }

So what's the difference?

PaperBirdMaster
  • 12,806
  • 9
  • 48
  • 94
aob
  • 197
  • 8
  • `static' was deprecated in previous standard c++0x. However, it was rectified as to C++11 standard. Basically they are doing the same job (i.e., static linkage). http://stackoverflow.com/questions/4726570/deprecation-of-the-static-keyword-no-more – 101010 May 13 '14 at 12:52

1 Answers1

3

Since it's const, then both have internal linkage, and there is no difference. So let's consider the more interesting case where it's not const.

In that case, then practically, there's little difference.

Technically, the first would have internal linkage, so the name can't be accessed from another translation unit; the second would have external linkage, but can't be accessed from another translation unit since its surrounding namespace can't be named.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • 2
    And in this particular case (a `const` not declared `extern`), they will actually both have internal linkage... – Angew is no longer proud of SO May 13 '14 at 12:56
  • 1
    In C++98 that had an impact on templates. Only pointers to objects with external linkage might be used as non-type template arguments. – ach May 13 '14 at 12:56
  • @AndreyChernyakhovskiy: Indeed, I thought about mentioning that, but my memory of obsolete standards is fading too quickly to be sure of the details of that particular weirdness. – Mike Seymour May 13 '14 at 12:59
  • I've developed the (almost certainly bad) habit of including `static` in addition to `namespace {` simply as a hint to the linker. I'm not confident that it's smart enough to realize the contents of unnamed namespaces are inaccessible elsewhere, and my links take so long that I'm willing to grasp at straws. – dlf May 13 '14 at 13:04
  • @MikeSeymour, that's the only thing that has ever been different _in practice_ I know of. In C++11, it seems, there is no _practical_ difference. – ach May 13 '14 at 13:56