cmake 和 Visual Studio 15 2017 生成器 - 定义构建类型

cmake and Visual Studio 15 2017 generator - defining a build type

我在 Windows 10 上工作。我将 cmake 与 Visual Studio 15 2017 生成器一起使用。 CMakeLists.txt 需要定义 CMAKE_BUILD_TYPE,因为它被从 cmake (execute_process) 调用的 Conan 命令使用。这是 cmake 命令:

cmake -DCMAKE_BUILD_TYPE=Release -G "Visual Studio 15 2017" ..

当我 运行 以这种方式构建命令时:

cmake --build .

我收到以下错误:

error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MTd_StaticDebug' in Tests.obj

Conan 安装了一个发布库 (MT_StaticRelease) 但 CMAKE_BUILD_TYPE 在构建过程中被忽略了。当我使用以下命令时构建工作:

cmake --build . --config Release

它是如何工作的?什么时候必须定义 --config buildType ?其他生成器呢,例如 Ninja?

Visual Studio是一个多配置系统。这意味着构建类型在构建时被 select 编辑,比方说当您使用 IDE 时,您可以在那时 select Release 或 Debug 配置和构建。因此,当您使用 cmake -G "Visual Studio ..." 生成 Visual Studio 解决方案(项目生成或配置步骤)时,CMake 没有 CMAKE_BUILD_TYPE.

的值

因此 CMake 调用需要因系统而异:

在 Visual Studio 等多配置环境中,您仅使用 1 个构建文件夹:

$ mkdir build && cd build # assume we are in the folder containing CMakeLists.txt
$ cmake .. -G "Visual Studio 15 2017 Win64" # Unless building for 32 bits, add the Win64 
$ cmake --build . --config Release # Or open IDE, change config to Release and build 
$ cmake --build . --config Debug

在 gcc 和 Makefiles 等单一配置环境中,您需要为每个配置使用 1 个文件夹

$ mkdir build_release && cd build_release # assume we are in the folder containing CMakeLists.txt
$ cmake .. -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release
$ cmake --build . 
$ cd .. && mkdir build_debug && cd build_debug
$ cmake .. -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Debug
$ cmake --build . 

另一个问题是 MT(静态)Visual Studio 运行时的定义。可能是您在您的 Conan 配置文件 compiler.runtime=MT 中定义的,或者它是由您的 CMakeLists.txt 直接设置的。柯南没有安装这样的静态 MT_StaticRelease 库,它是 Visual Studio 的一部分。如果您尝试静态 link visual studio 环境,您使用的配置文件应该如下所示:

# for debug
$ conan install .. -s build_type=Debug -s compiler.runtime=MTd
# for release
$ conan install .. -s build_type=Release -s compiler.runtime=MT