0

I'm writing a library in C++, which supports C++11 or later. Luckily, with C++14 it can avoid certain external dependencies. So, I would like to build it with newer C++ if that's available, but I can live with C++11.

How can I express this in CMake? i.e. how can I tell it to set "the highest C++ standard version that you can manage, but no less than C++11"?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

1

with C++14 it can avoid certain external dependencies.

So you firstly need to check, whether C++14 is supported or not. According to the result of the checks, your may build your library with C++14, if it is supported, or with C++11 with additional dependency.

if(cxx_std_14 IN_LIST CMAKE_CXX_KNOWN_FEATURES)
  # C++14 is available. Use it.
  set(CMAKE_CXX_STANDARD 14)
  # ...
else()
  # C++14 is not available. Resort to C++11.
  # ... add external dependency
  set(CMAKE_CXX_STANDARD 11)
  # ...
endif()

The snippet above uses CMAKE_CXX_KNOWN_FEATURES variable for check whether it includes a feature or not. Note, that this variable is set after the project() call.

Tsyvarev
  • 60,011
  • 17
  • 110
  • 153
  • Ah, but I want the requirement to go _forward_ and apply to dependent targets, so I don't want to check when at configuration-time of my project. – einpoklum Feb 02 '20 at 23:06
  • Your question was how to tell CMake to set "the highest C++ standard version that you can manage, but no less than C++11". And that's what @Tsyvarev answer does. You may define the c++ standard as an [interface definition](https://cmake.org/cmake/help/v3.0/prop_tgt/INTERFACE_COMPILE_DEFINITIONS.html) (and export your library target) to be applied to your library future dependents. – Former contributor Feb 04 '20 at 20:24
  • A "version of C++ standard" is not the same as a "version of the dependent library". If several versions of the library is available, one may link with the highest version (assuming the library's versions are backward-compatible), because it probably contains fewer bugs and has better performance. But higher C++ standard doesn't mean the better quality of the compiled library: bugs and performance are property of the **compiler**, which isn't changed when select a standard version. In that case using minimal supported version is perfectly acceptable. – Tsyvarev Feb 04 '20 at 21:37
  • The code snippet in the answer post checks for C++14 only for avoid additional dependencies you need in case of C++11. Once you decide whether additional dependencies are needed, selecting C++ standard is no longer free: if you **don't use** additional dependencies, C++14 is the minimal supported version by your library; if you **use** additional dependencies, then C++14 can no longer be used and C++11 is the only choice. – Tsyvarev Feb 04 '20 at 21:41