I wanted to write a little Unit-test system with CMake that I can easily copy and paste in all my projects so I came up with this:
include(CMakeParseArguments)
set(UNIT_TEST "unit_tests")
add_custom_target(${UNIT_TEST} ALL VERBATIM)
function(add_unit_test dependency)
cmake_parse_arguments(UT_ "" "NAME" "" ${ARGN})
if(NOT ${UT_NAME})
set(${UT_NAME} ${ARG0})
endif()
add_test(${ARGN})
add_dependencies(${UNIT_TEST} ${dependency})
add_custom_command(TARGET ${UNIT_TEST}
COMMENT "Run tests"
POST_BUILD COMMAND ctest
ARGS -R ${UT_NAME} --output-on-failures
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
VERBATIM)
endfunction(add_unit_test)
I hoped that it would work fine like that and run all unit tests I would add in my project by calling add_unit_test(dep ...)
with a dependency to compile before and then the same arguments as for add_test(...)
. In reality this error shows up:
CMake Warning (dev) at cmake/testing.cmake:13 (add_custom_command):
Policy CMP0040 is not set: The target in the TARGET signature of
add_custom_command() must exist. Run "cmake --help-policy CMP0040" for
policy details. Use the cmake_policy command to set the policy and
suppress this warning.
The target name "unit_tests" is unknown in this context.
Call Stack (most recent call first):
source/test/CMakeLists.txt:10 (add_unit_test)
This warning is for project developers. Use -Wno-dev to suppress it.
Why exactly is the target unknown at this point? include(cmake/testing.cmake)
is the first thing I call after cmake_minimum_required
in my project build script, so it can't be because add_custom_target(${UNIT_TEST} ALL VERBATIM)
hasn't been called yet.
Is there a way I can add a custom command to the UNIT_TEST target?