Prohibit cmake build on the top-level source

Viewed 35

I would like to prohibit cmake in-source build especially at top-level. For example prohibited case is cmake -S . -B ., however, I would like to allow cmake -S . -B build Thus, these following options are not fitted here.

set(CMAKE_DISABLE_SOURCE_CHANGES ON)
set(CMAKE_DISABLE_IN_SOURCE_BUILD ON)

I added small script in CMakeLists.txt

get_filename_component(srcdir "${CMAKE_SOURCE_DIR}" REALPATH)
get_filename_component(bindir "${CMAKE_BINARY_DIR}" REALPATH)
if("${srcdir}" STREQUAL "${bindir}")
    message(FATAL_ERROR "Do not build on the top of the sources")
endif()

It works, but CMakeCache.txt and CMakeFiles are still created. How can I keep my sources clean? With git, git clean -d -f -x can help me, but I would like to have a solution with cmake itself.

1 Answers

"CMakeCache.txt and CMakeFiles are still created" -- you cannot avoid this with CMake <=3.24, the latest development version at time of writing. You can suggest deleting that folder and file in your FATAL_ERROR message.

if(CMAKE_SOURCE_DIR STREQUAL CMAKE_BINARY_DIR)
    message(FATAL_ERROR "Out of source builds required with CMake. "
            "Please clean up the CMakeFiles/ directory and CMakeCache.txt file.")
endif()
Related