Using different compiler flags when using different compilers, VS generator

Working in an MSVC/Visual Studio shop but we need to start building using multiple compilers (Clang, Intel, etc). Using the VS generator works ok, eg:

cmake -B build-dir-intel -G “Visual Studio 17” -T “Intel C++ Compiler 2024”
cmake -B build-dir-clang -G “Visual Studio 17” -T “ClangCl”
cmake -B build-dir-143 -G “Visual Studio 17” -T “v143”
cmake -B build-dir-142 -G “Visual Studio 17” -T “v142”

Works fine, but we want to be able to change compiler flags depending on the compiler being used: ie when using the Intel Compiler, we want to use /O3 in release builds rather than /O2.

I don’t want to have to go into the generated vcxproj files and do this manually, and need to find a neat and scalable way of doing this. So far I’ve been unable to. Trying to set the

CMAKE_CXX_FLAGS_RELEASE

flag via the command line doesn’t work. I tried to create a toolchain file containing just:

set(CMAKE_CXX_FLAGS_RELEASE_INIT “${_MD} /O3 /Ob2 /DNDEBUG”)

and then specifing this toolchain file with the -DCMAKE_TOOLCHAIN_FILE when calling cmake. However this results in the following entry in the cache:

CMAKE_CXX_FLAGS_RELEASE:STRING=/O3 /Ob2 /DNDEBUG /O2 /Ob2 /DNDEBUG

It seems that line 481 of <cmake_install_dir>\Modules\Platform\Windows-MSVC.cmake is being applied AFTER my toolchain file is processed - this is the line:

  string(APPEND CMAKE_${lang}_FLAGS_RELEASE_INIT "${_MD} /O2 /Ob2 /DNDEBUG")

ie it’s appending “/O2 /Ob2 /DNDEBUG” those settings to what I already set. I don’t really know what to do - it seems whatever I try, the pre-baked settings contained in the cmake installation will always get applied after anything I try to set myself, meaning I need to somehow edit the vcxproj files myself after cmake is done with them.

What can I do?