Reputation: 5856
What is the proper way to declare a constexpr constant in a source file? I'm split between two ways:
constexpr int ORDER = 1;
vs
namespace {
constexpr int ORDER = 1;
} // unnamed namespace
The reason I question the usefulness of wrapping into an unnamed namespace is because at global scope, constexpr
implies static
. So similar to how in header files writing
static constexpr int ORDER = 1;
makes static
just a repetition, I'm assuming that the same should apply in source files as well, hence internal linkage should be guaranteed for "constexpr
variables declared in a source file's global scope".
Is this the case? Are there different suggestions?
Upvotes: 4
Views: 2143
Reputation: 31577
It's not required to enclose constexpr
variables, declared in a source file, in an unnamed namespace. Since the end goal is to achieve internal linkage you have to remember this:
The name of an entity that belongs to a namespace scope has internal linkage if it is the name of
- a variable, variable template, function, or function template that is explicitly declared static; or
- a non-template variable of non-volatile const-qualified type, unless
- it is explicitly declared extern, or
- it is inline or exported, or
- it was previously declared and the prior declaration did not have internal linkage; or
- a data member of an anonymous union.
i.e since "constexpr
implies const
and const
on namespace scope implies internal linkage", it's superfluous to say
static constexpr int ORDER = 1;
or
namespace {
static constexpr int ORDER = 1;
}
If you want a tangible proof of the internal linkage property, consider this compilation error
Upvotes: 4