static data member "unresolved external symbol" if constexpr is used in its definition
| Bugzilla Link | 34754 |
| Resolution | FIXED |
| Resolved on | Dec 08, 2017 07:57 |
| Version | trunk |
| OS | Windows NT |
| CC | @majnemer,@DougGregor |
Extended Description
// header.h struct S { static int const i; };
// source.cpp #include "header.h" constexpr int const S::i = 0;
// main.cpp #include "header.h" int main() { return S::i; // error or OK, depending on "C++ Language Standard" in compiler options }
If compiled with clang and "ISO C++ Latest Draft Standard (/std:c++latest)": linker error "unresolved external symbol"
If compiled with clang and "ISO C++17 Standard (/std:c++17)" or "ISO C++14 Standard (/std:c++14)": OK
If compiled with VC: OK in all cases
I'm using Visual Studio 2017 on Windows 10 64-bit and the latest clang for Windows. Can someone tell me what's going on here? Is this a bug in clang? S::i has external linkage, but clang seems to transform it into internal linkage if constexpr is in the definition. Why?
This has been fixed. S::i is no longer considered an inline variable and hence has external linkage as in C++11/14.
For a static data member [dcl.inline] must very likely be interpreted as if it means "in the class definition". This lack of clarity might be a defect in the language.
C++17 has a new rule (http://eel.is/c++draft/dcl.constexpr#1):
A function or static data member declared with the constexpr specifier is implicitly an inline function or variable ([dcl.inline]).
My guess is that MSVC does not implement inline variables and is thus giving you the C++14 behavior.
But S::i is only defined constexpr, it is not declared constexpr. The declaration has no initializer, is thus no definition and thus not an inline variable.
It would be an inline variable in this case: struct T { static int constexpr i = /some constant expression/; };
I would expect that the constexpr definition of S::i has the additional benefit that S::i can be used in constant expressions in the translation unit of source.cpp. In all other translation units it is just an ordinary declared static data member and cannot be used there in constant expressions (because it is not defined in the definition of S with an initializer that is a constant expression).
C++17 has a new rule (http://eel.is/c++draft/dcl.constexpr#1):
A function or static data member declared with the constexpr specifier is implicitly an inline function or variable ([dcl.inline]).
My guess is that MSVC does not implement inline variables and is thus giving you the C++14 behavior.