Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static and anonymous namespace [duplicate]

Tags:

c++

Possible Duplicate:
Unnamed/anonymous namespaces vs. static functions

Is this completely redundant, or may there be a reason to do this?

namespace {
  static void f() {
    ...
  }
}
like image 586
Baruch Avatar asked Dec 02 '12 21:12

Baruch


1 Answers

It looks redundant to me -- either being declared static or being in an anonymous namespace means it has internal linkage.

§3.5/3:

A name having namespace scope (3.3.6) has internal linkage if it is the name of:
— a variable, function or function template that is explicitly declared static;

§3.5/4:

[...] An unnamed namespace or a namespace declared directly or indirectly within an unnamed namespace has internal linkage. [...] A name having namespace scope that has not been given internal linkage above has the same linkage as the enclosing namespace if it is the name of
— a variable; or
— a function; or

So, as it is right now, it has internal linkage because it's explicitly declared static. If it wasn't explicitly declared static, it would have internal linkage because it's declared inside an unnamed namespace. Same effect either way.

Note that here I'm replying specifically about a function -- there are a few obscure cases where there's a difference when you're dealing with the name of a type (e.g., class/struct/union), but I don't know of any such thing that applies in the case of a function.

As far as what internal linkage really means, that's one of those places the standard is actually quite direct and clear. It's probably best to quote the definitions of all three possibilities (§3.5/2):

  1. When a name has external linkage, the entity it denotes can be referred to by names from scopes of other translation units or from other scopes of the same translation unit.
  2. When a name has internal linkage, the entity it denotes can be referred to by names from other scopes in the same translation unit.
  3. When a name has no linkage, the entity it denotes cannot be referred to by names from other scopes.

Note that the italics above match those in the standard, which is its way of saying that these sentences define what those phrases mean throughout the rest of the standard.

like image 168
Jerry Coffin Avatar answered Sep 21 '22 07:09

Jerry Coffin