The following module may be useful to discover the MSVC toolchain:
- https://github.com/scikit-build/cmake-FindVcvars/blob/master/FindVcvars.cmake
- https://github.com/scikit-build/cmake-FindVcvars#readme
We use it to find the appropriate vcvars script and build external projects that do not use CMake.
A simple CMake script could be created that would use this module and allow you to do this:
cmake -P /path/to/ConfigureWithVisualStudioToolchain.cmake ^
-DGENERATOR=Ninja ^
-DPROJECT_SOURCE_DIR=/path/to/src ^
-DPROJECT_BINARY_DIR=/path/to/bld
To select a specific visual studio toolchain, you would pass options like -DVcvars_MSVC_VERSION=... -DVcvars_MSVC_ARCH= ....
The script ConfigureWithVisualStudioToolchain.cmake
would be something like this:
Note: I did not test the following code
# Sanity check
# TODO: Check that expected parameters are set ...
set(download_dir ${PROJECT_BINARY_DIR}/CMakeFiles/FindVcvars)
file(MAKE_DIRECTORY ${download_dir})
# Download FindVcvars.cmake
set(dest_file "${download_dir}/FindVcvars.cmake")
set(expected_hash "cacfcb6e243e4a0fa628c5873d0cb444c08079b7729af24093a59712b01b6ff6")
set(url "https://raw.githubusercontent.com/scikit-build/cmake-FindVcvars/v1.3/FindVcvars.cmake")
if(NOT EXISTS ${dest_file})
file(DOWNLOAD ${url} ${dest_file} EXPECTED_HASH SHA256=${expected_hash})
else()
file(SHA256 ${dest_file} current_hash)
if(NOT ${current_hash} STREQUAL ${expected_hash})
file(DOWNLOAD ${url} ${dest_file} EXPECTED_HASH SHA256=${expected_hash})
endif()
endif()
list(INSERT CMAKE_MODULE_PATH 0 ${download_dir})
find_package(Vcvars REQUIRED)
# TODO: Support passing argument like toolset, ...
execute_process(COMMAND
${Vcvars_LAUNCHER} ${CMAKE_COMMAND} -G ${GENERATOR} -S ${PROJECT_SOURCE_DIR} -B ${PROJECT_BINARY_DIR}
)