在 CMake 中检查 C 程序输出

ffe*_*rri 2 c c++ cmake

是否可以对程序的输出进行平台检查?

假设我想编译这个程序:

#include <library.h>
#include <iostream>
int main() {
    std::cout << LIBRARY_MAGIC_VALUE << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

并运行它(在 CMake 配置步骤中)以提取LIBRARY_MAGIC_VALUE.

如何编写平台检查(移至:此处)指南中,似乎没有考虑此用例,或者仅专门针对特定事物(例如检查类型的大小)。

我怎样才能实施这样的检查?

jot*_*tik 5

您可以使用 CMake 内置try_run命令,如下所示:

TRY_RUN(
    # Name of variable to store the run result (process exit status; number) in:
    test_run_result

    # Name of variable to store the compile result (TRUE or FALSE) in:
    test_compile_result

    # Binary directory:
    ${CMAKE_CURRENT_BINARY_DIR}/

    # Source file to be compiled:
    ${CMAKE_CURRENT_SOURCE_DIR}/test.cpp

    # Where to store the output produced during compilation:
    COMPILE_OUTPUT_VARIABLE test_compile_output

    # Where to store the output produced by running the compiled executable:
    RUN_OUTPUT_VARIABLE test_run_output)
Run Code Online (Sandbox Code Playgroud)

这会尝试编译并运行给定的检查test.cpp。您仍然需要检查是否try_run成功编译并运行检查,并适当处理输出。例如,您可以执行以下操作:

# Did compilation succeed and process return 0 (success)?
IF("${test_compile_result}" AND ("${test_run_result}" EQUAL 0))
    # Strip whitespace (such as the trailing newline from std::endl)
    # from the produced output:
    STRING(STRIP "${test_run_output}" test_run_output)
ELSE()
    # Error on failure and print error message:
    MESSAGE(FATAL_ERROR "Failed check!")
ENDIF()
Run Code Online (Sandbox Code Playgroud)