Multi-project
- C++ course
- Advanced
- Lesson 46/83
- 5 min
Learn multi-project structure with CMake.
Multi-project structure
Large projects split into multiple subdirectories: each has its own CMakeLists.txt. The top-level file includes subdirectories with the add_subdirectory command. This keeps the code modular.
Typical layout: a root CMakeLists.txt, a lib/ subdirectory for the library, an app/ subdirectory for the application. The root file calls add_subdirectory(lib) and add_subdirectory(app). Each subdirectory CMakeLists defines its own targets. Variable and target sharing between parent and child is automatic.
Library and application separation
In a modular project the lib/ directory defines a library with add_library. The app/ directory defines the application with add_executable and links to the library with target_link_libraries. This lets the library be reused in other projects.
Example: in lib/CMakeLists.txt write add_library(mylib utils.cpp). In app/CMakeLists.txt write add_executable(myapp main.cpp) and target_link_libraries(myapp PRIVATE mylib). The root file calls both with add_subdirectory. The dependency direction is clear: app depends on lib; lib is independent.
Practice Write the multi-project root file
Write the root CMakeLists.txt. Add cmake_minimum_required(VERSION 3.20) and project(MyApp). Include two subdirectories with add_subdirectory(lib) and add_subdirectory(app).
Starter code
# CMakeLists.txt (root)
# Add cmake_minimum_required, project and add_subdirectorySample solution
cmake_minimum_required(VERSION 3.20)
project(MyApp)
add_subdirectory(lib)
add_subdirectory(app)Expected output
Project structure ready
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does add_subdirectory do?
- Creates a new library
- Processes a subdirectory's CMakeLists Correct answer
- Sets the output directory
- Changes the compiler
Explanation: add_subdirectory brings a subdirectory's CMakeLists.txt into the build.
2 Match each piece to its role
| Term | Meaning |
|---|---|
add_subdirectory(lib) |
Adds the lib directory |
add_subdirectory(app) |
Adds the app directory |
lib/CMakeLists.txt |
Library target |
app/CMakeLists.txt |
Application target |
3 Complete the add_subdirectory command
____(lib)
add_subdirectory(lib)
Explanation: add_subdirectory(lib) brings the lib directory into the build.