-
Notifications
You must be signed in to change notification settings - Fork 3.4k
[C++ runtime] Fix static const ODR violations #2848
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Defining a static const member in a header breaks ODR, as the object will be defined in every translation unit that includes the header. Instead, the members should either be declared `inline` (which is implicitly the case for `constexpr` members) or initialized in a cpp. Alternatively, using an anonymous enum allows the definition to remain inside the header meaning that the compiler can still choose to inline values.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@nburles All you changed were anonymous enums before, so what does your patch improve?
@mike-lischke You mean these bits? e.g.
I'm happy to change them to remove the static casts and any reference to VS2013 in the comments? |
Yes, that was the original thought I had when I spoke of Visual Studio, but then I remembered this is also compiled on other platforms :-) |
True... the C++20 version will definitely work on any compiler which supports C++20 - but it could be safer to leave the pre-C++20 version as it is for now then? (Unless there's a CI system which uses each of the supported toolchains?) |
We definitely need to keep pre-C++20 support. Currently we even guarantee C++11. That needs to be carefully weigh up when to require C++17 as minimal version. I would love to get more feedback on that from the community. Can you also say a word about why you changed the enums to constexpr since that seems to make no difference (unless I miss something here)? |
Without this change, the original code was e.g.:
If the header file containing this line is included in more than one translation unit (very likely!) then it introduces undefined behaviour. Each translation unit ends up with its own copy of With C++20 (guarded by
ensures that there is only a single copy of Pre-C++20,
|
@parrt This C++ patch is ready to be merged. |
Thanks for all good work guys. |
Defining a static const member in a header breaks ODR, as the object will be defined in every translation unit that includes the header.
Instead, the members should either be declared
inline
(which is implicitly the case forconstexpr
members) or initialized in a cpp. Alternatively, using an anonymous enum allows the definition to remain inside the header meaning that the compiler can still choose to inline values.