non-inline namespace cannot be reopened as inline

619 Views Asked by At

I'm having an issue understanding compiler's complaint:

namespace
{
}

inline namespace
{
}

gcc says

inline namespace must be specified at initial definition

and MSVC says what's in the title.

My disarray comes from my expectation that two subsequent anonymous namespaces should be considered a new declaration of an unrelated new space, yet the compiler complains that somehow they're linked, like if it was trying to extend the first one with the second.

https://godbolt.org/z/rwAYLg

1

There are 1 best solutions below

5
On

Each anonymous namespace in a translation unit is the same namespace.

For:

namespace
{
  struct F {};
}

namespace
{
  struct G {};
}

The compiler effectively generates something like this:

namespace __mytranslation_unit_anonymous_namespace
{
  struct F {};
}

namespace __mytranslation_unit_anonymous_namespace
{
  struct G {};
}

F and G are both in the same namespace. If you copy the code to a new translation unit the compiler will generate a new namespace name e.g. __mytranslation_unit2_anonymous_namespace.