【问题标题】:How to print a message exactly once per cmake invocation?如何每次 cmake 调用只打印一次消息?
【发布时间】:2020-04-04 05:13:52
【问题描述】:

希望在使用时使包 foobar 打印到找到它的位置

find_package(foobar CONFIG)

我正在使用

find_package_message(foobar
  "Found foobar: ${info} (version ${foobar_VERSION})"
  "[${info}][${foobar_VERSION}]"
)

使用find_package_message 的想法是 打印此消息一次。

但是,我想在每次从头开始运行 cmake 时打印它。 我只想在 cmake 的同一次运行中避免重复。

find_package_message在缓存中存储一​​个变量(FIND_PACKAGE_MESSAGE_DETAILS_foobar) 包含上述第三个参数的值 ("[${info}][${foobar_VERSION}]") 和 当该变量不存在或更改时再次打印消息。

所以,第二次运行 cmake 的结果是什么都没有打印出来:FIND_PACKAGE_MESSAGE_DETAILS_foobar 已经存在于缓存中并且没有改变。

如何解决此问题,以便在每次 新调用 cmake 时打印一条消息?

【问题讨论】:

  • 不能使用自己的变量吗? if(NOT foobar_my_variable_message_already_printed) set(foobar_my_variable_message_already_printed TRUE) message(..) endif()?
  • 那不会是一个全局变量吧?因此,如果 -say- 一个子目录包含一个也执行 find_package(foobar) 的项目,该消息仍将被打印。

标签: cmake


【解决方案1】:

函数find_package_message 用于打印一次消息,直到更改“详细信息”。为了实现不同的语义 - 每个cmake 调用打印一次消息 - 使用这个功能有点意思,但实现你自己的一个。

为了区分第一个函数调用和其他函数调用,可以检查是否定义了 GLOBAL property:

function(print_message_once name message)
  # Name of the custom GLOBAL property to check
  set(pname PRINT_MESSAGE_ONCE_DUMMY_${name})
  get_property(prop_defined GLOBAL PROPERTY ${pname} DEFINED)
  if (NOT prop_defined)
    message(STATUS "${message}")
    # Define a property so next time it will exist
    define_property(GLOBAL PROPERTY ${pname} BRIEF_DOCS "${name}" FULL_DOCS "${name}")
  endif()
endfunction()

注意,这个函数不再需要details 参数。在单个cmake 调用期间,第一次找到包后清除缓存并使用不同参数执行第二次搜索的可能性很小。

或者,代替属性检查,可以检查函数的存在:

function(print_message_once name message)
  # Name of the custom function to check
  set(fname _check_first_dummy_${name})
  if (NOT COMMAND ${fname})
    message(STATUS "${message}")
    # Define a function so next time it will exist
    function(${fname})
    endfunction()
  endif()
endfunction()

函数 print_message_once 的使用(上面使用 2 种方式中的任何一种定义)与 find_package_message 的“兼容”是

if(NOT foobar_FIND_QUIETLY)
  print_message_once(foobar
    "Found foobar: ${info} (version ${foobar_VERSION})"
  )
endif()

如果需要,检查XXX_FIND_QUIETLY 变量(反映find_package() 调用的QUIET 选项)可以合并到print_message_once 函数本身中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    相关资源
    最近更新 更多