CMake:如何指定要使用的 Visual C++ 版本?

CMake: how to specify the version of Visual C++ to work with?

我安装了 Visual Studio 的多个版本(2010、2012、2015 试用版)。

如何强制 CMake 为特定的 VS 版本生成 makefile?默认情况下,它为 VS2015 生成。

cmake -G "Visual Studio 12" ..\MyProject

首先你可以检查 generators 你的 CMake 版本支持什么(以及它们是如何命名的):

> cmake.exe --help
...
The following generators are available on this platform:
...
  Visual Studio 11 2012 [arch] = Generates Visual Studio 2012 project files.
                                 Optional [arch] can be "Win64" or "ARM".    
...

然后你可以给生成器

  1. cmake.exe -G "Visual Studio 11" ..(简称)
  2. cmake.exe -G "Visual Studio 11 2012" ..(全名)

我更喜欢后者,因为它更清晰。我通常在构建脚本包装器中进行此调用:

@ECHO off
IF NOT EXIST "BuildDir\*.sln" (
    cmake -H"." -B"BuildDir" -G"Visual Studio 11 2012"
)
cmake --build "BuildDir" --target "ALL_BUILD" --config "Release"

全名被传输到内部缓存的 CMake 变量名 CMAKE_GENERATOR。所以上面的调用等同于

  1. cmake -DCMAKE_GENERATOR="Visual Studio 11 2012" ..

这给了我们一个有趣的可能性。如果将名为 PreLoad.cmake 的文件与主 CMakeLists.txt 文件并行放置,则可以强制将默认值(如果可用)用于您的项目

  1. cmake.exe ..

    PreLoad.cmake

    if (NOT "$ENV{VS110COMNTOOLS}" STREQUAL "")
        set(CMAKE_GENERATOR "Visual Studio 11 2012" CACHE INTERNAL "Name of generator.")
    endif()
    

有时您可能还需要添加 -T <toolset-name>-A <platform-name> 选项:

  1. cmake.exe -G "Visual Studio 10" -T "v90" ..

最后但同样重要的是,如果您真的只对编译器感兴趣

  1. "\Program Files (x86)\Microsoft Visual Studio 11.0\VC\vcvarsall.bat"

    cmake.exe -G "NMake Makefiles" ..


参考资料

  • CMake command line
  • What is the default generator for CMake in Windows?
  • How can I generate a Visual Studio 2012 project targeting Windows XP with CMake?