除打破既定预期外,为何不建议用$CACHE{variable}访问CMake缓存变量?
关于CMake中
$CACHE{variable}使用的疑问 我在学习《Professional CMake》时,书中“5.5 - 变量的潜在意外行为”章节提到:除临时调试场景外,不建议使用$CACHE{variable}访问缓存变量,理由是这会打破“普通变量覆盖缓存变量值”的长期既定预期。
对此我存在疑问,因此编写了两个示例验证:
方法1
cmake_minimum_required(VERSION 3.27) project(example) set(variable "Hello" CACHE STRING "An example variable" FORCE) set(variable "Goodbye") message("The normal variable's value is ${variable}.") message("The cache variable's value is $CACHE{variable}.")
方法2
cmake_minimum_required(VERSION 3.27) project(example) set(variable "Hello" CACHE STRING "An example variable" FORCE) set(variable "Goodbye") message("The normal variable's value is ${variable}.") unset(variable) message("The cache variable's value is ${variable}.")
两个示例的输出结果一致:
The normal variable's value is Goodbye. The cache variable's value is Hello. -- Configuring done (0.0s) -- Generating done (0.0s) -- Build files have been written to: ...
我认为$CACHE{variable}能更明确表达开发者意图,也难以理解为何会引发混淆。我在谷歌及CMake 3.27官方文档中都未找到相关说明。
目前我倾向于在所有CMakeLists.txt中使用简洁的$CACHE{variable}访问缓存变量,想了解除“打破既定预期”外,是否还有其他不建议使用的理由?
内容的提问来源于stack exchange,提问作者Toggy Smith
相关产品推荐
相关产品推荐

