[CMake] How do I create targets first and add sources later?

Nicholas Braden nicholas11braden at gmail.com
Thu Jan 14 15:57:22 EST 2016


I often find it more convenient to call add_library() and
add_executable() first, apply properties to them etc., and then later
add the sources to them with target_sources() (usually in other CMake
files via add_subdirectory). Obviously, all my targets will eventually
have sources added.

However, CMake completely errors out as soon as it sees me creating a
target with no sources - it doesn't even care that I am adding sources
to it later. Example:
"You have called ADD_LIBRARY for library mylib without any source
files. This typically indicates a problem with your CMakeLists.txt
file"

I have been working around this by adding a dummy source file or
adding one of the sources ahead of time, but this is somewhat
inconvenient.

Is there a better way to do this? Alternatively, could CMake be
changed to allow creating a target that initially has no sources as
long as it eventually has sources added to it?

Note: I am familiar with the approach of gathering a list of source
files before creating the target, but this is really inconvenient to
do across multiple files in multiple directories. It is easier to call
target_sources() instead.


More information about the CMake mailing list