You can use the CMake built-in try_run command as follows:
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)
This attempts to compile and run the given check in test.cpp. You still need to check whether try_run succeeded to compile and run the check, and handle the output appropriately. For example, you can do something like this:
# 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()