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
.
constexpr
for functions implies inline
, which implies external linkage. So you already have what you want for bar
. As for baz
and bing
, you can also declare them inline in C++17.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.