c++cmakecmakelists-options

Specify different CMAKE_CXX_STANDARD for unit tests


I have a program that requires in its top-level CMakeLists.txt:

set(CMAKE_CXX_STANDARD 11)

This cannot be touched. I introduced unit tests to this project using the catch2 framework, and created an integration tests that requires std::filesystem. But this requires a higher C++ standard. So I added into tests/CMakeLists.txt:

set(CMAKE_CXX_STANDARD 17)

set(headers
  catch.hpp
  )

set(source  
  main.cpp
  date_test.cpp
  climate_test.cpp
)
...

But this does not do the trick. Is this even something that is possible? Or do you have another suggestion? Apparently it would take much effort to have people upgrade their C++ so I can raise the version everywhere. But the tests are important and I want them to run on our CI server.

Thanks for any hints!


Solution

  • The CMAKE_CXX_STANDARD variable is (like many other CMAKE_* variables) only the default value for target-specific settings.

    So it is indeed possible to set the C++ standard for a single target to a different value. As documented here, the following line does the trick:

    set_property(TARGET tgt PROPERTY CXX_STANDARD 17)

    PS: As pointed out in the comments you should think about the question, if it is a good idea to run the tests with another C++ version than the code itself.