If you structure your project as follows:
project | |- CMakeLists.txt |- core | | | |- core.cc | |- core.h | |- CMakeLists.txt | |- example1 | | | |- example1.cc | |- CMakeLists.txt | |- example2 | |- example2.cc |- CMakeLists.txt
Your project/CMakeLists.txt file just includes the other cmakelists files
project/CMakeLists.txt:
cmake_minimum_required (VERSION 3.5) project (project CXX C) add_subdirectory(core) add_subdirectory(example1) add_subdirectory(example2)
Your core/CMakeLists.txt file builds the core targets
project/core/CMakeLists.txt:
add_library(core core.cc) target_include_directories(core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
Your exampleN/CMakeLists.txt file builds the example targets
project/example1/CMakeLists.txt:
add_executable(example1 example.cc) target_link_libraries(example1 core)
When you generate the build files, cmake mimics your directory structure in the build directory, so running the following commands would result in the below directory structure:
$ cd project $ mkdir build $ cd build $ cmake ..
The resulting directory structure would look as follows:
project | |- CMakeLists.txt |- core | | | |- core.cc | |- core.h | |- CMakeLists.txt | |- example1 | | | |- example1.cc | |- CMakeLists.txt | |- example2 | | | |- example2.cc | |- CMakeLists.txt | |- build | |- Makefile |- core | |- Makefile | |- example1 | |- Makefile | |- example1 | |- example2 |- Makefile |- example2
Now if you only want to build example2 for example, you can execute the following:
$ cd project/build/example2 $ make
The benefit of this is that it doesn't pollute your source tree with build files. If you want to blow away the build directory, you only need to delete one directory
$ rm -r project/build