Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>(In the following, the <strike>striked-through</strike> things are stuff that does not apply anymore to C++11, but did apply to C++03. C++11 makes almost no differences anymore (if there are, they are just language lawyer differences which I can't recall).). </p> <p>Unnamed namespaces are a utility to make an identifier <strike>effectively</strike> translation unit local. They behave as if you would choose an unique name per translation unit for a namespace:</p> <pre><code>namespace unique { /* empty */ } using namespace unique; namespace unique { /* namespace body. stuff in here */ } </code></pre> <p>The extra step using the empty body is important, so you can already refer within the namespace body to identifiers like <code>::name</code> that are defined in that namespace, since the using directive already took place. </p> <p>This means you can have free functions called (for example) <code>help</code> that can exist in multiple translation units, and they won't clash at link time, <strike>since they all got an unique name due to their unique namespace they are in</strike>. The effect is almost identical to using the <code>static</code> keyword used in C which you can put in in the declaration of identifiers. <strike><code>static</code> used in that manner is deprecated in C++, since</strike> unnamed namespaces are a superior alternative, being able to even make a type translation unit local. </p> <pre><code>namespace { int a1; } static int a2; </code></pre> <p>Both <code>a</code>'s are translation unit local and won't clash at link time. But the difference is that the <code>a1</code> in the anonymous namespace <strike>just</strike> gets an unique name. <strike>It has still external linkage and may be exported into the symbol table of the object file being created. This becomes important if you want to use its address as a template argument:</p> <pre><code>template&lt;int * ptr&gt; struct sample { }; // OK - a1 has external linkage sample&lt;&amp;a1&gt; s1; // NOT OK - translation unit locality is done by giving a2 internal linkage. sample&lt;&amp;a2&gt; s2; </code></pre> <p>Template parameters has to have external linkage so in this case the identifier has to be put into an anonymous namespace.</strike></p> <p>Read the excellent article at comeau-computing <a href="http://www.comeaucomputing.com/techtalk/#nostatic" rel="noreferrer">`Why is an unnamed namespace used instead of static?</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload