Can CMake automatically detect RH devtoolset-7?

I am building on Centos 7, which natively has gcc 4.8.5, using CMake 3.16.6 and Ninja. My code requires gcc 7 so I specify RH devtoolset-7:

-DCMAKE_CXX_COMPILER=/opt/rh/devtoolset-7/root/usr/bin/g++

My code checks the compiler version as follows:

if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
    if (CMAKE_CXX_COMPILER_VERSION VERSION_LESS 5.4.0)
        message(FATAL_ERROR "g++ (GCC) version must be at least 5.4.0 (detected ${CMAKE_CXX_COMPILER_VERSION}). If on Centos 7, have you enabled Red Hat Developer ToolSet7? (-DCMAKE_CXX_COMPILER=/opt/rh/devtoolset-7/root/usr/bin/g++)")
    endif()
endif()

I want to handle this automatically so that the user doesn’t need to worry about which Linux platform he/she is using. Do I need to check the version of gcc myself in CMakeLists.txt as shown above, and adapt the shown code to change the compiler path, or should CMake detect devtoolset-7 automatically?

CMake doesn’t generally support the compiler changing out from underneath it like that, so no. Erroring is the most reliable way to handle this case.

How could it? The scl mechanism is a lot like Visual Studio command prompts and toolchains must be loaded in the environment for use before running CMake (for non-IDE generators). The same thing is true with compilers made available via module load: they need to be loaded before running CMake to configure (and build) a project.

Thanks for your explanation, I’ll consider using CXX instead.