It is possible to specify a RELATIVE
flag and a directory to a file( GLOB ... )
command. Although not mentioned directly in the documentation of file( GLOB ), this works for file( GLOB_RECURSE ... )
too. Note, I tested this on my windows setup. I don't known about *nix.
- Together with some get_filename_component calls with
NAME_WE
and/orPATH
flags, it is now possible to reconstruct the name and the relative path of the cpp-file with respect to the globbing dir. - Extracting a path and a name (without extension) is mostly similar
to the answer by Massimiliano. In addition, I have used his
suggestion to generate a unique testname with
string( REGEX REPLACE ... )
; replacing forward slashes by underscores. - With a unique test-name, the executable can be generated and afterwards its output directory can be modified with set_target_properties.
Check this and this question for more info on modifying the output directory.
file( GLOB_RECURSE TEST_CPP_SOURCES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.cpp )
foreach( test_case ${TEST_CPP_SOURCES} )
# Get the name without extension
get_filename_component( test_name ${test_case} NAME_WE )
# Get the path to the test-case, relative to the ${CMAKE_CURRENT_SOURCE_DIR}
# thanks to the RELATIVE flag in file( GLOB_RECURSE ... )
get_filename_component( test_path ${test_case} PATH )
message( STATUS " name = " ${test_name} )
message( STATUS " path = " ${test_path} )
# I would suggests constructing a 'unique' test-name
string( REPLACE "/" "_" full_testcase "${test_name}/${test_path}" )
# Add an executable using the 'unique' test-name
message( STATUS " added " ${full_testcase} " in " ${test_path} )
add_executable( ${full_testcase} ${test_case} )
# and modify its output paths.
set_target_properties( ${full_testcase} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${test_path} )
endforeach( test_case ${TEST_CPP_SOURCES} )