1

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

v.oddou
  • 6,476
  • 3
  • 32
  • 63
  • In this commit https://patchwork.ozlabs.org/project/gcc/patch/5a5c09f5-1e45-8b63-bed9-7e9531519abd@acm.org/ Nathan Sidwell deleted the concept of reopening a anonymous namespace. Sounds good though, he also created the error I'm hitting. Sounds kinda wrong to not check `new_ns` idk – v.oddou Jun 10 '20 at 07:05

1 Answers1

1

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.

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • surprising. later you meant: "if you copy to a new unit"? – v.oddou Jun 10 '20 at 07:23
  • @v.oddou sorry, yes – Alan Birtles Jun 10 '20 at 07:25
  • I found this in the standard 10.3.1.1 `where inline appears if and only if it appears in the unnamed-namespace-definition and all occurrences of unique in a translation unit are replaced by the same identifier, and this identifier differs from all other identifiers in the translation unit. The optional attribute-specifier-seq in the unnamed-namespace-definition appertains to unique` It's undecipherable. – v.oddou Jun 10 '20 at 08:04
  • @v.oddou - There's an example in the paragraph bellow. Even for `namespace A { namespace {} }` - the identifier is still the same. SO you'll get `A::__mytranslation_unit1_anonymous_namespace` – StoryTeller - Unslander Monica Jun 10 '20 at 08:24
  • @StoryTeller-UnslanderMonica yes the example is clear but there is no rationale as to why all anonymous namespaces (of the same level) are identified by the same ID. – v.oddou Jun 10 '20 at 16:07