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

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

提问人:Pietro 提问时间:11/25/2015 更新时间:11/26/2015 访问量:39721

问:

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

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

visual-studio visual-c++ cmake 版本

评论


答:

2赞 Pietro 11/25/2015 #1
cmake -G "Visual Studio 12" ..\MyProject
34赞 Florian 11/26/2015 #2

首先,您可以检查您的 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" ..

这给了我们一个有趣的可能性。如果将一个名为 parallel 的文件放置在主文件旁边,则可以强制将默认文件(如果可用)用于您的项目PreLoad.cmakeCMakeLists.txt

  1. cmake.exe ..

    预加载.cmake

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

有时,您可能需要添加 also 或选项:-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" ..


引用

评论

0赞 Herve Mutombo 7/2/2018
一个重要问题的重要答案。+1 给你。
0赞 Royi 8/19/2018
有没有办法将生成器设置为MSVC,但使其使用CLANG作为编译器?似乎无论我做什么,我都无法让 CMake 使用不同的编译器(尽管它是兼容的)。-G"Visual Studio 15 2017 Win64"
0赞 JustWe 3/5/2021
这对我不起作用,我指出但仍然显示-G"Visual Studio 15 2017 Win64"-- The C compiler identification is MSVC 19.16.27045.0 -- The CXX compiler identification is MSVC 19.16.27045.0