4

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".

Mike T
  • 41,085
  • 18
  • 152
  • 203
Dan M.
  • 3,818
  • 1
  • 23
  • 41
  • 6
    `check if a given CMakeLists was included by the other or if it's a "root".` - You may compare `CMAKE_SOURCE_DIR` with `CMAKE_CURRENT_SOURCE_DIR` for check whether currently executed `CMakeLists.txt` is top-level one. Usually, appropriate README file is suffucient - with CMake you hardly can be protected from all possible misusages. – Tsyvarev Apr 09 '16 at 00:17
  • You could define a variable in the root CMakeLists and check for it in the subdirectory. – usr1234567 Apr 09 '16 at 07:31
  • You could check with `if (TARGET ...)` if a depending project was already processed/does exist. Or you add the dependencies needed by `project` directly with `add_subdirectory()` (which has its downsides) or as an external project (for more details see [here](http://stackoverflow.com/questions/31512485/cmake-how-to-setup-source-library-and-cmakelists-txt-dependencies)). – Florian Apr 09 '16 at 17:39
  • What do you mean with dependencies in your case? Third party libraries? If you are talking about another library that you also compile, CMake will figure out the dependencies and build them before. – ToniBig Apr 10 '16 at 18:08
  • Well, I have a `CMakeLists` in the project root with adds as a sub-directories all needed dependencies, but the "problem" is that most of the stuff related to my projects is sitting in the `root/project` folder which I add a subdirectory to, so some users haven't read the readme (unsurprisingly =) ) and instead of running cmake in the root folder tried to build it from subfolder which obviously failed (since it couldn't link to unbuilt dependencies). So I wanted a clean way to prevent such use case (maybe there was already built-in way of doing so). – Dan M. Apr 10 '16 at 18:36

1 Answers1

3

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()
Mike T
  • 41,085
  • 18
  • 152
  • 203