Friday, November 12, 2021

[SOLVED] CMake - Create executable for all *.cpp file in folder

Issue

I have this folder tree:

benchmark/
├─ pair/
│  ├─ benchmark_create.cpp
│  ├─ benchmark_insert.cpp
│  ├─ benchmark_remove.cpp
├─ set/
├─ CMakeLists.txt

And this is my current CMakeLists.txt file content:

add_executable(dbg_pair_creation pair/benchmark_creation)
target_link_libraries(pair_creation benchmark::benchmark)

add_executable(dbg_pair_insert pair/benchmark_insert)
target_link_libraries(pair_insert benchmark::benchmark)

add_executable(dbg_pair_remove pair/benchmark_remove)
target_link_libraries(pair_remove benchmark::benchmark)

There is a compacxt way to do the same and to put this executable in a folder with name pair that is the folder name of the source?


Solution

You could use a foreach loop.

set(benchmarks creation insert remove)
foreach (benchmark IN LISTS benchmarks)
  add_executable(dbg_pair_${benchmark} pair/benchmark_${benchmark}.cpp)
  target_link_libraries(dbg_pair_${benchmark} PRIVATE benchmark::benchmark)
  set_property(
    TARGET dbg_pair_${benchmark}
    PROPERTY RUNTIME_OUTPUT_DIRECTORY 
             "${CMAKE_CURRENT_BINARY_DIR}/dbg_pair_${benchmark}"
  )
endforeach ()

Then you would just need to add to the benchmarks list when you add a new benchmark.



Answered By - Alex Reinking