【问题标题】:Cannot set variables in generated CMake script无法在生成的 CMake 脚本中设置变量
【发布时间】:2017-06-04 07:58:48
【问题描述】:

我试图从CMake 中的可执行文件的调用中获取输出作为构建系统中处理的字符串。这是一个测试套件列表,我将使用 add_test 添加到 CTest 工具中。

CMakeLists.txt

...(After adding the mlpack_test target)...
configure_file(generate_test_names.cmake.in generate_test_names.cmake)
add_custom_command(TARGET mlpack_test
  POST_BUILD
  COMMAND ${CMAKE_COMMAND} -P generate_test_names.cmake
)

generate_test_names.cmake.in

function(get_names)
  message("Adding tests to the test suite")
  execute_process(COMMAND ${CMAKE_BINARY_DIR}/bin/mlpack_test --list_content
    OUTPUT_VARIABLE FOO)
  message(STATUS "FOO='${FOO}'")
endfunction()

get_names()

脚本被执行,我可以在构建的stdout 中看到来自mlpack_test --list_content 的输出。但是FOO 仍然是一个空字符串。

输出:

Adding tests to the test suite
ActivationFunctionsTest*
    TanhFunctionTest*
    LogisticFunctionTest*
    SoftsignFunctionTest*
    IdentityFunctionTest*
    RectifierFunctionTest*
    LeakyReLUFunctionTest*
    HardTanHFunctionTest*
    ELUFunctionTest*
    SoftplusFunctionTest*
    PReLUFunctionTest*
-- FOO=''

为什么OUTPUT_VARIABLE 的参数没有用执行进程的stdout 初始化?

【问题讨论】:

  • 很可能,您在构建输出中看到的是已执行进程的stderr。您可以为execute_process 传递附加选项ERROR_VARIABLE FOO,因此它的整个输出 将被重定向到FOO 变量中。
  • 我试过你的建议,但FOO 仍然是空的。我还注意到我无法在脚本中定义任何变量,即。即使set(myvar 1) myvar 为空。
  • 命令configure_file 替换${var}所有出现 ...您可能希望将@ONLY 参数传递给命令,因此它将仅替换@var@实例。顺便说一句,您可以检查生成文件generate_test_names.cmake的内容。
  • @Tsyvarev 非常感谢!添加@ONLY 有效。应该更仔细地检查configure_file 的文档。
  • @Tsyvarev 您介意将其添加为问题的答案吗? :)

标签: cmake ctest


【解决方案1】:

使用configure_file 生成CMake 脚本时,最好为该命令使用@ONLY 选项:

configure_file(generate_test_names.cmake.in generate_test_names.cmake @ONLY)

在这种情况下,只有@var@ 引用将被替换为变量的值,但${var} 引用保持不变

function(get_names)
  message("Adding tests to the test suite")
  # CMAKE_BINARY_DIR will be replaced with the actual value of the variable
  execute_process(COMMAND @CMAKE_BINARY_DIR@/bin/mlpack_test --list_content
    OUTPUT_VARIABLE FOO)
  # But FOO will not be replaced by 'configure_file'.
  message(STATUS "FOO='${FOO}'")
endfunction()

get_names()

【讨论】:

    猜你喜欢
    • 2014-01-29
    • 2011-11-26
    • 2011-01-28
    • 2020-12-05
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 2017-03-09
    相关资源
    最近更新 更多