Overriding CMAKE_CXX_COMPILER with VS2017 on Windows 10

Is there a way to specify a custom compiler on Windows 10 using Visual Studio
2017, and not use the one inside the VS2017 installation? Below are my
attempts to do so.

Using CMake 3.17.3 on Windows 10 and Visual Studio 2017 I have failed to
override CMAKE_CXX_COMPILER in multiple ways.

  1. I used set(CMAKE_CXX_COMPILER "absolute/path/to/custom/cl.exe") at the
    top of my CMakeLists.txt file before the project() command. The
    project() command overwrites the CMAKE_CXX_COMPILER to the cl.exe
    inside the VS2017 installation. This is the approach I would prefer.
  2. I specified -D CMAKE_CXX_COMPILER=absolute/path/to/custom/cl.exe at the
    command line to the same effect.

I have the following toy project set up to test this behavior.

cmake_minimum_required(VERSION 3.15)

set(CMAKE_C_COMPILER "D:/compiler/cl.exe")
set(CMAKE_CXX_COMPILER "D:/compiler/cl.exe")




add_executable(hello main.cpp)

I was using an out-of-source build and before every attempt I deleted the
entire build directory.

It does not matter whether I specify “Visual Studio 15 2017” as the generator,
or let CMake automatically find and select it, the project command will
always overwrite the values in CMAKE_C_COMPILER and CMAKE_CXX_COMPILER.
Using cmake-gui or the command line yields the same result.

Using then cmake --build build --verbose I can see, that it’s always the
compiler detected by CMake that is invoked, and not the custom one I am trying
to use.

This was already discussed in this other topic: