cmake: add_subdirectory() vs include()

The most commonly used rule is “One CMakeLists.txt per target”. So your option No. 1.

To achieve this your project structure may have to adapt, if “each source file from the subfolders creates a separate executable”.

And the root CMakeLists.txt is your starting point and contains the project() command.

It’s important to note that

  • CMake will mirror your add_subdirectory() and CMakeLists.txt directory structure in its generated build environment
  • CMake will create a new variable scope with each add_subdirectory() call (the big difference to using include() command)

What you should avoid is having to reference source files out of other subdirectories with something like ../some_other_dir/some_other_source.cpp. It shows that your CMake structure is not setup according to the rule of thumb quoted above.

Documentation Extracts

  1. CMake: add_subdirectory() command

    Add a subdirectory to the build. The source_dir specifies the directory in which the source CMakeLists.txt and code files are located.

  2. CLion: CMakeLists File

    When a project has the complex structure and includes one or more subdirectories (project root and subdirectories), you can create subdirectory CMakeList.txt files. Subdirectory CMakeLists.txt files describe the build, contents, and target rules for a subdirectory.

  3. C++Now 2017: Daniel Pfeifer “Effective CMake: a random selection of best practices

    Directories that contain a CMakeLists.txt are the entry point for the build system generator. Subdirectories may be added with add_subdirectory() and must contain a CMakeLists.txt too.

References

  • Embracing Modern CMake
  • https://stackoverflow.com/questions/2186110/cmake-tutorial
  • CMake with subdirectories
  • CMake share library with multiple executables
  • Renaming `CMakeLists.txt`

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)