Issue
I'm building a C++ library with CMake. Is it possible to set the C++ standard to the newest released standard supported by the user's compiler? I checked href="https://cmake.org/cmake/help/latest/prop_tgt/CXX_STANDARD.html" rel="nofollow noreferrer">the docs for the variable CXX_STANDARD, but it only shows how to use one specific standard.
Motivation:
I want my library to be compatible with C++11, but I also want to use the features of newer C++ standards if they're available. For example, I have defined the following macro.
#if (__cplusplus > 201700L || _MSVC_LANG > 201700L)
#define IF_CONSTEXPR_MACRO if constexpr
#else
#define IF_CONSTEXPR_MACRO if
#endif
This is great for header-only libraries because
- The code is compatible with old C++ standards, and
- If the user compiles with C++17 or newer, they get all the advantages of constexpr if.
Unfortunately, my library is not header only. I want the resulting .so file to use the if constexpr
version if it is available.
Solution
For MSVC, you can wrap a compiler ID generator expression around /std:c++latest
. For the other compilers you might need to do multiple checks with CheckCXXCompilerFlag
. Honestly, if the compiler version used to compile your target really doesn't matter, it would be a lot simpler to just tell your user to use whatever they want / have.
I'm getting some XY problem vibes from the scenario you've described. If the code using that macro is equally valid with if
or if constexpr
, then you don't really need if constexpr
there, and can probably just trust your compiler to do optimizations (which I assume is what you're trying to achieve with that macro).
Answered By - starball Answer Checked By - David Goodson (WPSolving Volunteer)