c++ – Why do you need an unnamed namespace?

Question:

what benefits can be derived from such a construction:

namespace{
    int i;
}

Answer:

The benefit is the same as using the static — avoiding problems with the one definition rule (ODR) . If, for example, in the title you have int i; , then when connecting to 2 or more .cpp files, you will receive a link error – the same symbol is defined twice. If you write static int i; , then i will become local to every object file that i gets into – i.e. each cpp will have its own i , unlike the first option, where i one for the whole program. The same happens when you write

namespace{
    int i;
}

i gets internal linking and therefore there will be no problem with the ODR.

Scroll to Top