I want my source organised in a number of subdirectories but be able to create a single executable without having to build a library for each subdirectory. Can CMake do this? Something like:
ADD_EXECUTABLE(foo a/main.cpp a/other.cpp b/another.cpp)
Is it that simple? With the / working as a directory separator regardless of platform?
Another (arguably better for big code bases) variant is to use a separate
CMakeLists.txt
for each sub-directory where you isolate adding sources of the directory to a target usingtarget_sources
and maybe some particular configuration settings \ include conditions for those sources:here you also have more control of the scope by specifying
PRIVATE
, other options areINTERFACE
orPUBLIC
. See details here: https://cmake.org/cmake/help/v3.3/command/target_sources.htmlHere the my simple example
Yes, that would work.
Update: What follows is not very relevant anymore because nowadays CMake supports response files, so there shouldn't be problems with too long command lines.
However you might have troubles when the number of files get too high, and the command line too long for your compiler to be able to handle it. A possible solution is to add a static library for each subdirectory, add them to a list "ALL_MY_SUB_LIBS", and link them to the main target foo in this way:
ld linker question: the --whole-archive option