You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CMakePresets.json中引用CMakeCommon.json的变量?

解决CMakePresets引用公共配置变量的问题

CMake Presets本身不支持在cacheVariables中直接引用其他自定义cache变量(比如你想在MYLIB_PATH里用${MYLIB_VERSION}),因为预设解析阶段这些自定义cache变量还未被处理。这里有两种可行的解决办法:

方法一:用环境变量传递公共值

把公共版本号定义为环境变量,在预设中通过环境变量引用:

  1. 修改CMakeCommon.json,定义一个隐藏的基础预设,把版本号放在environment字段里:
{
  "version": 5,
  "cmakeMinimumRequired": {
    "major": 3,
    "minor": 25,
    "patch": 1
  },
  "configurePresets": [
    {
      "name": "common-base",
      "hidden": true,
      "environment": {
        "MYLIB_VERSION": "1_0"
      }
    }
  ]
}
  1. 在CMakePresets.json的default预设中继承这个common-base,然后在cacheVariables里用${env:MYLIB_VERSION}引用环境变量:
{
  "version": 5,
  "cmakeMinimumRequired": {
    "major": 3,
    "minor": 25,
    "patch": 1
  },
  "include": [
    "CMakeCommon.json"
  ],
  "configurePresets": [
    {
      "name": "default",
      "inherits": "common-base",
      "displayName": "Default Config",
      "description": "Default config generator with ninja",
      "generator": "Ninja",
      "binaryDir": "${sourceDir}/build/${presetName}",
      "hidden": true,
      "cacheVariables": {
        "CMAKE_TOOLCHAIN_FILE": "MyPath/vcpkg/scripts/buildsystems/vcpkg.cmake",
        "VCPKG_DEFAULT_TRIPLET": "x64-windows",
        "CMAKE_EXPORT_COMPILE_COMMANDS": "TRUE",
        "MYLIB_PATH": "D:/MyLib/${env:MYLIB_VERSION}"
      },
      "environment": {}
    },
    {
      "inherits": "default",
      "name": "debug",
      "displayName": "Debug",
      "description": "Debug build.",
      "cacheVariables": {
        "CMAKE_BUILD_TYPE": "Debug"
      }
    },
    {
      "inherits": "default",
      "name": "release",
      "displayName": "Release",
      "description": "Release build.",
      "cacheVariables": {
        "CMAKE_BUILD_TYPE": "Release"
      }
    }
  ],
  "buildPresets": [
    {
      "name": "Debug",
      "configurePreset": "debug"
    },
    {
      "name": "Release",
      "configurePreset": "release"
    }
  ],
  "testPresets": []
}

方法二:在CMake脚本中生成路径

不在预设里直接定义MYLIB_PATH,而是在CMakeLists.txt中读取公共版本号并生成路径:

  1. 保持CMakeCommon.json不变(依然在cache变量中定义MYLIB_VERSION)。

  2. 在项目的CMakeLists.txt开头添加以下代码,自动设置MYLIB_PATH:

# 读取公共配置中的MYLIB_VERSION,生成库路径
if(NOT DEFINED MYLIB_PATH)
  set(MYLIB_PATH "D:/MyLib/${MYLIB_VERSION}" CACHE PATH "Path to MyLib")
endif()

这种方式利用CMake的运行时变量替换,完美规避预设解析阶段的限制,也是更符合CMake常规流程的做法。

内容的提问来源于stack exchange,提问作者Jepessen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:40:41