I've got a bunch of cpp files, each contains a main function. I just wish to compile all of them in the patter like:
add_executable(algorithm1 algorithm1.cpp)
add_executable(algorithm2 algorithm2.cpp)
...
add_executable(findFile findFile.cpp)
I hope there's simplier way to avoid very similar lines. I need sth like
add_executable(EXTRACT_FROM_FILENAME xxx.cpp)
one line for all.
My question: can we achieve to compile/link and get the executable which name is from the source file? I know Makefile has similar funtionality, what about CMake? So next time I add a new cpp file, I don't have to modify this CMakeLists.txt file, and it will automatically compile the new file to target executable, with corresponding filename.
Thanks a lot.
CodePudding user response:
cmake_minimum_required(VERSION 3.4)
project(Troskyvs LANGUAGES CXX)
file(GLOB one_file_sources RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} "*.cpp")
foreach(file_path ${one_file_sources})
get_filename_component(filename "${file_path}" NAME)
add_executable("${filename}" "${file_path}")
set_target_properties("${filename}" PROPERTIES
CXX_STANDARD 17
CXX_STANDARD_REQUIRED ON
LINKER_LANGUAGE CXX)
endforeach()
CodePudding user response:
Something like this would work and avoid the many pitfalls of globbing in CMake.
cmake_minimum_required(VERSION 3.20)
project(example)
function(MyProj_add_tool filename)
cmake_path(GET filename STEM target)
add_executable("${target}" "${filename}")
endfunction()
MyProj_add_tool(algorithm1.cpp)
MyProj_add_tool(algorithm2.cpp)
# ...
MyProj_add_tool(findFile.cpp)
See the documentation for cmake_path
here: https://cmake.org/cmake/help/latest/command/cmake_path.html#get-stem