Currently I have a project that needs C 17, therefore in the CMakeLists.txt I have this line pretty early on:
set(CMAKE_CXX_STANDARD 17)
From the command line (cmake) once in a while I want to test that the project also compiles with C 20. (to avoid surprises).
How can I choose to compile with C 20 from command line?
If I do cmake -DCMAKE_CXX_STANDARD=20 then it is later overwritten by the configuration instead of 17 being interpreted as just a minimum requirement.
I could check if the variable is predefined to avoid overwritting but I was looking for a more declative way to specify this.
(I am using cmake around 3.18.)
CodePudding user response:
The solution is to remove that set command and use target properties instead:
# set(CMAKE_CXX_STANDARD 17)
target_compile_features(myexecutable PUBLIC cxx_std_17)
Then, setting -DCMAKE_CXX_STANDARD=20 on the terminal should work again.
CodePudding user response:
Make CMAKE_CXX_STANDARD a cache variable. This allows you to easily specify a default that can be overwritten via the command line. Note that you need to make sure no "normal" CMAKE_CXX_STANDARD variable is available, since this value would take precedence over the cache variable.
set(CMAKE_CXX_STANDARD 17 CACHE STRING "the C standard to use for this project")
add_library(...)
Using cmake -D CMAKE_CXX_STANDARD=20 binary_dir should allow you to update the standard now, cmake -U CMAKE_CXX_STANDARD binary_dir should revert back to the default.
Alternatively you could create a custom cache variable. This would make a reuse easier, since it would allow you to overwrite the property, even if someone else sets CMAKE_CXX_STANDARD before using add_subdirectory to add your project.
set(MYPROJECT_CXX_STANDARD 17 CACHE STRING "the C standard to use for myproject")
# overwrite possibly preexisting value for this directory and subdirectories
set(CMAKE_CXX_STANDARD ${MYPROJECT_CXX_STANDARD})
add_library(...)
