6

Using CMake, I have a series of executables that are built, then added as tests, like this:

set(TestID 1)
add_executable (Test${TestID} Test${TestID}.cpp)

# Create test
configure_file(${TestID}.endf ${TestID}.endf COPYONLY)
add_test( NAME ${TestID} COMMAND Test${TestID} )

This works fine—the executables are created and the tests are correctly added. However, I don't want the test executables to be added to the all target.

Instead of having my tests built along with everything else, I would like them built right before the execution of the tests; maybe as part of make test or as part of ctest.

How can I do this?

4

1 回答 1

7

在创建测试可执行目标时设置EXCLUDE_FROM_ALL标志以从目标中排除all目标:

add_executable (Test${TestID} EXCLUDE_FROM_ALL Test${TestID}.cpp)

确保在执行测试之前构建测试目标更加棘手。您不能使用 向内置test目标添加依赖项add_dependencies,因为该test目标属于仅存在于创建的构建系统中的一组保留目标(如all,以及其他一些目标)。clean

作为一种变通方法,您可以使用TEST_INCLUDE_FILES目录属性在运行测试之前触发所需测试可执行文件的构建。BuildTestTargets.cmake.in在源目录中创建一个文件,内容如下:

execute_process(COMMAND "@CMAKE_COMMAND@" --build . --target Test1)
execute_process(COMMAND "@CMAKE_COMMAND@" --build . --target Test2)

然后将以下代码添加到您的CMakeLists.txt

configure_file("BuildTestTargets.cmake.in" "BuildTestTargets.cmake")
set_directory_properties(PROPERTIES TEST_INCLUDE_FILES
    "${CMAKE_CURRENT_BINARY_DIR}/BuildTestTargets.cmake")

BuildTestTargets.cmake然后,CTest 将在运行测试之前作为第一步包含并运行该文件。

于 2015-05-08T18:00:51.540 回答