With cmake, how would you disable in-source builds?

Viewed 18287

I want to disallow people from cluttering our source tree with generated CMake files... and, more importantly, disallow them from stepping on existing Makefiles that are not part of the same build process we're using CMake for. (best not to ask)

The way I have come up with to do this is to have a few lines at the top of my CMakeLists.txt, as follows:

if("${PROJECT_SOURCE_DIR}" STREQUAL "${PROJECT_BINARY_DIR}")
   message(SEND_ERROR "In-source builds are not allowed.")
endif("${PROJECT_SOURCE_DIR}" STREQUAL "${PROJECT_BINARY_DIR}")

However, doing it this way seems too verbose. Additionally, if I try an in-source build it still creates the the CMakeFiles/ directory, and the CMakeCache.txt file in the source tree before the error is thrown.

Am I missing a better way to do this?

8 Answers

I think I like your way. The cmake mailing list does a good job at answering these types of questions.

As a side note: you could create a "cmake" executable file in the directory which fails. Depending on whether or not "." is in their path (on linux). You could even symlink /bin/false.

In windows, I am not sure if a file in your current directory is found first or not.

Just make the directory read-only by the people/processes doing the builds. Have a separate process that checks out to the directory from source control (you are using source control, right?), then makes it read-only.

This is still the best answer for my purposes:

project(myproject)

if(PROJECT_SOURCE_DIR STREQUAL PROJECT_BINARY_DIR)
  message(FATAL_ERROR "In-source builds are not allowed")
endif()

or allow the build, but show a warning message:

if(PROJECT_SOURCE_DIR STREQUAL PROJECT_BINARY_DIR)
  message(WARNING "In-source builds are not recommended")
endif()

However, there does not appear to be a simple way to avoid CMakeFiles/ and CMakeCache.txt being created in the source directory.

Related