Best Practice for Ninja build Visual Studio?

Note: CMAKE_MINIMUM_REQUIRED(VERSION 3.21)

What is the recommended way to configure/invoke CMake such that it will use Ninja as the build tool but still locate the compiler/etc the way it would if you had specified the Visual Studio Code generator to use msbuild?

This isn’t just about forgetting to start a developer command prompt/pwsh, but it’s very common from desktop applications using the system/user paths, such as VS Code:

[cmake] CMake Error at CMakeLists.txt:14 (PROJECT):
[cmake]   No CMAKE_CXX_COMPILER could be found.

To reproduce:

  1. Open a prompt and confirm it does not have the vsdev environment variables loaded, and you cannot run cl.exe
  2. Ensure that ninja is in your path (e.g nuget/choco install it, or copy your vsdev ninja into c:\windows or something)
  3. Ensure cmake is in your path
  4. Create a trivial Hello World project
  5. cmake -G Ninja . build