I am trying to create a namespace-scope constant with external linkage
// in some include file:
namespace foo
{
constexpr double bar() { return 1.23456; } // internal linkage
constexpr double baz = 1.23456; // internal linkage
const double bing = 1.23456; // internal linkage
}
Is this even possible?
Yes, and no; you can use extern
:
[C++11: 3.5/3]:
A name having namespace scope (3.3.6) has internal linkage if it is the name of
- a variable, function or function template that is explicitly declared
static
; or,- a variable that is explicitly declared
const
orconstexpr
and neither explicitly declaredextern
nor previously declared to have external linkage; or- a data member of an anonymous union.
So:
namespace foo
{
extern constexpr double bar() { return 1.23456; }
extern constexpr double baz = 1.23456;
}
In your other translation unit, you should now be able to declare the function's name and refer to it:
#include <iostream>
namespace foo
{
extern constexpr double bar();
}
int main()
{
std::cout << foo::bar() << '\n';
}
However, the rules for constexpr
variables state that you cannot have a declaration that is not also a definition:
[C++11: 7.1.5/9]:
Aconstexpr
specifier used in an object declaration declares the object asconst
. Such an object shall have literal type and shall be initialized. [..]
So, you cannot take the same approach with baz
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With