Search code examples
buildcmakebuild-process

CMake: How to prevent using wrong subdirectory CMakeLists directly?


For example, if I have one main CMakeLists that builds all the dependencies of project and then builds project itself via add_subdirectory( project ). But if you try to build via project/CMakeLists you'd fail (because of missing dependencies). SO what is the best way to prevent this scenario, e.g. check if a given CMakeLists was included by the other or if it's a "root".


Solution

  • In the CMakeLists.txt file in the subdirectory where this is required, add:

    if("${CMAKE_SOURCE_DIR}" STREQUAL "${CMAKE_CURRENT_SOURCE_DIR}")
      message(FATAL_ERROR "Blah blah wrong directory")
    endif()