What is the difference in using unnamed namespace and global declaration?
Is there any specific context for using these two?
Can we access unnamed namespace components in external source files?
The point of an unnamed namespace is to provide a unique namespace within a translation unit (= a source file) without requiring an explicit prefix. This allows you to guarantee that your global names won't clash with other, equal global names in other translation units.
For example:
// file1.cpp
namespace
{
void foo() { /* ... */ }
}
#include "bar.h"
int do_stuff()
{
foo();
bar();
return 5;
}
// file2.cpp
namespace
{
void foo() { /* ... */ }
}
#include "bar.h"
int do_something else()
{
bar();
foo();
return 12;
}
You can link those two translation units together and know for certain that the two names foo
will refer to the function defined in the respective file, and you do not violate the one-definition rule.
Technically, you can think of an unnamed namespace as something like this:
namespace unique_and_unknowable_name
{
// ...
}
using namespace unique_and_unknowable_name;
Without this tool, the only way you could guarantee a non-violation of ODR would be to use static
declarations. However, there's a subtle difference, in that static
affects linkage, while namespaces do not.
static
affects linkage, while namespaces do not." What are the implications of that difference? –
Audly static
function has internal linkage; otherwise it has external linkage. So functions in an unnamed namespace have external linkage, just unknowable names. –
Acceptable All names declared inside an unnamed namespace have internal linkage (even names defined with an extern specifier).
© 2022 - 2024 — McMap. All rights reserved.
const static
s? – Uneven