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?

1
  • `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). stackoverflow.com/questions/4726570/… Commented May 13, 2014 at 12:52

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

And in this particular case (a const not declared extern), they will actually both have internal linkage...
In C++98 that had an impact on templates. Only pointers to objects with external linkage might be used as non-type template arguments.
@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.
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.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.