actual
actual

Reputation: 13

How can I use cmake to compile multiple source files and generate multiple executable files named after these file names

Currently, I need help either creating a CMakeList.txt, or simply figuring out the cmake command for the following.

I have some source files in the same directory, called A.cpp, B.cpp, C.cpp, D.cpp. I need to compile these such that the executables are named as A, B, C, D, respectively.

I want to use CMake to automatically traverse the directory and generate the corresponding executable file instead of adding the corresponding executable file in CMakeList.txt every time I add a file.

Upvotes: 1

Views: 3480

Answers (1)

Bitwize
Bitwize

Reputation: 11210

This is a bit of an odd request. Usually I'd suggest manually writing add_executable where needed since it's more maintainable.

In CMake, there isn't really a good way to collect all files in a directory. You can use file(GLOB ...) to grab all files; but this gets done at configure time, and if you introduce new sources then CMake won't detect the new source and won't reconfigure automatically or build the new sources without explicitly being told to reconfigure.

If you're able to discretely list each source, it would be better. But otherwise what you are requesting can be done with a combination of a foreach through each source file using get_filename_component to get the file name and passing it to add_executable

set(source_files src/a.cpp src/b.cpp src/c.cpp ...)

# Loop through each source file
foreach(source_file IN LISTS source_files)
    # Get the name of the file without the extension (e.g. 'a' from src/a.cpp'
    get_filename_component(target_name ${source_file} NAME_WE)
    
    # Create an executable with the above name, building the above source
    add_executable("${target_name}" "${source_file}"
endforeach()

If discretely listing the source files isn't possible, you can use file(GLOB...) or file(GLOB_RECURSE):

file(GLOB source_files "src/*.cpp")

But again; this prevents automatically detecting when new sources get added, and I don't recommend it.

Upvotes: 4

Related Questions