Add Source in a subdirectory to a cmake project

Since CMake 3.1 there is a new way to add source from subdirectories: target_sources

Say you have root_dir and root_dir/sub_dir and source files in both. With target_sources you can do this:

In root_dir/CMakeLists.txt define the target

add_library(some_target main.cpp)
add_subdirectory(sub_dir)

In root_dir/sub_dir/CMakeLists.txt add sources:

target_sources(some_target PRIVATE more_cool_stuff.cpp)

some_target will now contain both source files.

It is also possible to use other commands in root_dir/sub_dir/CMakeLists.txt using some_target, for example target_compile_definitions which is quite convenient to add compilation definitions.

I learned about target_sources here, check it out if you want more explanation and examples

Leave a Comment