CMakeToolchain: 使用 Conan 生成的文件扩展 CMakePresets¶
在本示例中,我们将了解如何扩展您自己的 CMakePresets 以包含 Conan 生成的文件。
注意
本示例中使用 CMake 预设。这需要 CMake >= 3.23,因为从 CMakeUserPresets.json
到 CMakePresets.json
的 “include” 仅在该版本之后受支持。如果您不想使用预设,可以使用类似的方法
cmake <path> -G <CMake generator> -DCMAKE_TOOLCHAIN_FILE=<path to
conan_toolchain.cmake> -DCMAKE_BUILD_TYPE=Release
如果您无法使用预设功能,每次运行 conan install
时,Conan 都会显示确切的 CMake 命令。
请首先克隆源代码以重新创建此项目。您可以在 GitHub 的 examples2 仓库中找到它们
$ git clone https://github.com/conan-io/examples2.git
$ cd examples2/examples/tools/cmake/cmake_toolchain/extend_own_cmake_presets
请打开 conanfile.py 并检查它是如何设置 tc.user_presets_path = 'ConanPresets.json'
的。通过修改 CMakeToolchain 的此属性,您可以更改生成的预设的默认文件名。
def generate(self):
tc = CMakeToolchain(self)
tc.user_presets_path = 'ConanPresets.json'
tc.generate()
...
现在您可以提供您自己的 CMakePresets.json
,以及 CMakeLists.txt
CMakePresets.json¶
{
"version": 4,
"include": ["./ConanPresets.json"],
"configurePresets": [
{
"name": "default",
"displayName": "multi config",
"inherits": "conan-default"
},
{
"name": "release",
"displayName": "release single config",
"inherits": "conan-release"
},
{
"name": "debug",
"displayName": "debug single config",
"inherits": "conan-debug"
}
],
"buildPresets": [
{
"name": "multi-release",
"configurePreset": "default",
"configuration": "Release",
"inherits": "conan-release"
},
{
"name": "multi-debug",
"configurePreset": "default",
"configuration": "Debug",
"inherits": "conan-debug"
},
{
"name": "release",
"configurePreset": "release",
"configuration": "Release",
"inherits": "conan-release"
},
{
"name": "debug",
"configurePreset": "debug",
"configuration": "Debug",
"inherits": "conan-debug"
}
]
}
注意 "include": ["./ConanPresets.json"],
以及每个预设如何 inherits
Conan 生成的预设。
现在我们可以为 Release 和 Debug 安装(以及其他配置,如果我们想要的话,也可以借助 build_folder_vars
)
$ conan install .
$ conan install . -s build_type=Debug
并且通过使用**我们自己的预设**来构建和运行我们的应用程序,这些预设扩展了 Conan 生成的预设
# Linux (single-config, 2 configure, 2 builds)
$ cmake --preset debug
$ cmake --build --preset debug
$ ./build/Debug/foo
> Hello World Debug!
$ cmake --preset release
$ cmake --build --preset release
$ ./build/Release/foo
> Hello World Release!
# Windows VS (Multi-config, 1 configure 2 builds)
$ cmake --preset default
$ cmake --build --preset multi-debug
$ build\\Debug\\foo
> Hello World Debug!
$ cmake --build --preset multi-release
$ build\\Release\\foo
> Hello World Release!