60

Given I have defined an executable with its main source file in a CMakeList.txt file:

ADD_EXECUTABLE(MyExampleApp main.cpp)

Can I add further source files to this executable after this line but in the same or an included CMakeList.txt file?

Torbjörn
  • 5,512
  • 7
  • 46
  • 73
  • 3
    Normally you do that using variables instead of files on your ADD_EXECUTABLE() line. – drescherjm Feb 18 '12 at 16:00
  • 4
    @drescherjm gave correct answer - just gather your sources with `list(APPEND SOURCES src.cpp src2.cpp)` or `set(SOURCES src.cpp)` and `set(SOURCES ${SOURCES} src2.cpp)`. – arrowd Feb 18 '12 at 18:02
  • Thanks. I was doing it like that but it seemed somehow bruteforce. Anyway. It's working. – Torbjörn Feb 18 '12 at 21:33

3 Answers3

88

Use target_sources, available since cmake 3.1

eg. target_sources(MyExampleApp PRIVATE ${extra_file})

https://cmake.org/cmake/help/v3.1/command/target_sources.html

Mark Ingram
  • 71,849
  • 51
  • 176
  • 230
ACyclic
  • 5,904
  • 6
  • 26
  • 28
  • 5
    If the target is a library (not executable) this trick also works, but you should use `PRIVATE` instead of `PUBLIC`, otherwise the particular source file will get linked twice. – Mark Lakata Mar 23 '17 at 00:20
  • 1
    @MarkLakata I've updated the answer to change it from `PUBLIC` to `PRIVATE`. – Mark Ingram Nov 22 '19 at 15:38
9

I think you may use:

add_executable(MyExampleApp main.cpp)
add_library(library STATIC ${ADDITIONAL_SOURCES})
set_target_properties(library PROPERTIES
     LIBRARY_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
target_link_libraries(MyExampleApp library)
dizel3d
  • 3,619
  • 1
  • 22
  • 35
  • It should be noted that this does not work for Windows resource (.rc) files out-of-the-box even though they can normally be provided as source files to `add_library()`. CMake complains that the "CMAKE_RC_CREATE_STATIC_LIBRARY" variable is not set. The workaround is to also include an empty .c source file. – Nathan Osman Jul 22 '15 at 02:47
4

It should be noted that for more recent versions of CMake (> 3.1 I think) one can append files to the SOURCES property on targets.

http://www.cmake.org/cmake/help/v3.3/prop_tgt/SOURCES.html

Jean-Michaël Celerier
  • 7,412
  • 3
  • 54
  • 75
  • 5
    Or you could just use [`target_sources()`](http://www.cmake.org/cmake/help/v3.3/command/target_sources.html?highlight=target_sources) (see DarthB's answer [here](http://stackoverflow.com/a/31541070/4763489)). – Florian Sep 10 '15 at 14:11