Is there a method to declare a namespace with the extern modifier so that the namespace's entire content is externally linked?
-
4All namespace scoped declarations are externally linked. – StoryTeller - Unslander Monica Feb 02 '22 at 09:56
-
That is not the way the `extern` keyword works, take a look at https://stackoverflow.com/questions/10422034/when-to-use-extern-in-c. In C++ everything is linkable by default, the `static` keyword turn a variable or class as file local. – Bolo Feb 02 '22 at 10:00
-
1@StoryTeller-UnslanderMonica Using e.g. `namespace foo { int a; }` in a header file, and including that header file into multiple source files, will cause the `foo::a` variable to be defined in each translation unit. This is solved by turning the definitions into declarations, by doing `namespace foo { extern int a; }`. But if there's many variables in the namespace `foo` the OP wants to do something like `extern namespace foo { ... }` to make all variables in the namespace `extern` (I guess). – Some programmer dude Feb 02 '22 at 10:30
-
1@Physician Unfortunately it's not possible to make a whole namespace `extern`. You must declare all variables inside it separately. – Some programmer dude Feb 02 '22 at 10:31
1 Answers
You seem to be asking two questions. One regarding external linkage and one regarding the extern
specifier.
Regarding the linkage, there is not really a need for such a syntax.
External linkage is already the default at namespace scope, whether in the global namespace or another namespace, except for const
non-template non-inline variables and members of anonymous unions. (https://en.cppreference.com/w/cpp/language/storage_duration#internal_linkage)
So the other way around, syntax to make all names in a namespace have internal linkage, is more likely to be required and this is possible with unnamed namespaces
namespace {
//...
}
in which all declared names have internal linkage.
Regarding the extern
specifier used to turn a variable definition into just a declaration at namespace scope or to give it external linkage explicitly, I am not aware of any syntax to apply it to a whole namespace. You will have to specify it explicitly on each variable.

- 53,019
- 2
- 56
- 105