Search code examples
c++cmakemsys2

Is there a way to automatically set the add_executable's target name to it's source file name in CMake?


I'm quite new to CMake. I want to get the executable for some CPP files with their filename as their executable filename. For example output1.cpp gives the executable named output1. Currently I'm using the following lines in my CMakeLists.txt file.

add_executable(output1 output1.cpp)
add_executable(output2 output2.cpp)
add_executable(output3 output3.cpp)
.
.
.    
add_executable(outputN outputN.cpp)

I know there is a for loop solution for this. Like,

foreach(i RANGE 1 N)
    add_executable(output${i} output${i}.cpp)
endforeach()

But that's not what I'm looking for. I'm looking for a solution that does not require passing hardcoded target names. Is there a way to achieve this?


Solution

  • As @André pointed out in the comments, I was able to solve this by declaring a custom auto_add_executable function.

    function(auto_add_executable name)
        add_executable(${name} ${name}.cpp)
    endfunction()
    
    auto_add_executable(output1)
    auto_add_executable(output2)
    .
    .
    .
    auto_add_executable(outputN)