How to handle different CXX standards in the same project

Hey guys,
in our project we want to use the newest available CXX Standard. (We do not want some beta like std:c++latest but an official released standard.)
At the moment this is C++20.

Our project is build with different compilers. As mentioned above, we want to use the newest supported CXX Standard supported by the specific compiler. For some (old) compilers this would be CXX 17, for newer ones this would be CXX 20.
We are achieving this behaviour by directly setting.
set(CMAKE_CXX_STANDARD 20) directly after project()

However: it turns out that a single lib does not compile with C++20.
I have added
target_compile_features(${LIB_NAME} PRIVATE cxx_std_17)
to this lib but this does not seam to work

So my question is:
What is the best way to use the latest CXX Standard the compiler supports per default but also be able to overwrite the CXX standard for single libs if necessary.
:slight_smile:

Thx for your help :slight_smile:

Have you tried:
set_property(TARGET ${LIB_NAME} PROPERTY CXX_STANDARD 17)?

Thx that did work.
2 Questions regarding your proposal:

  1. in this case the overwrite only applies to the single target (and is not exposed to all targets which link to ${LIB_NAME} right?
  2. what is the difference between set_property and target_compile_features. i thought target_compile_features is the more modern way to do that?

Right. This is a target property, and properties are not inherited when you link to a target AFAIK.

I’m not sure. I proposed this method because CMAKE_CXX_STANDARD variable is used to initialize CXX_STANDARD property, so it’s only natural to overwrite that. It may be that when both thing are set, one of them just wins, or the newest standard will be chosen. Maybe some of the devs know.

thank you Jakub for your help and explanations.
I was just curious :wink: But if it works I’ll not question it :smiley:

Yes, CMake will use the standard that satisfies all requirements, both from the compile features and the CXX_STANDARD target property. In other words, it will pick the highest out all the ones specified.

1 Like

ah thx Craig for your explanations :slight_smile: