是否可以对程序的输出进行平台检查?
假设我想编译这个程序:
#include <library.h>
#include <iostream>
int main() {
std::cout << LIBRARY_MAGIC_VALUE << std::endl;
return 0;
}
并运行它(在CMake配置步骤中)以提取LIBRARY_MAGIC_VALUE
。
在How to write platform checks指南中,似乎没有考虑此用例,或仅专门用于特定事物(例如检查类型的大小)。
我该如何实施这样的检查?
答案 0 :(得分:2)
使用try_run命令进行此类检查:
try_run(LIBRARY_MAGIC_VAL_RUN_RESULT
LIBRARY_MAGIC_VAL_COMPILE_RESULT
${CMAKE_CURRENT_BINARY_DIR}/library_magic_val
"test_library_magic_val.c"
RUN_OUTPUT_VARIABLE LIBRARY_MAGIC_VAL_OUTPUT)
# Do not forget to check 'LIBRARY_MAGIC_VAL_RUN_RESULT' and
# 'LIBRARY_MAGIC_VAL_COMPILE_RESULT' for successfullness.
# Variable LIBRARY_MAGIC_VAL_OUTPUT now contains output of your test program.
答案 1 :(得分:1)
您可以使用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)
这会尝试编译并运行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()