Preventing "In-Source Builds"

In source builds are usually never desire by developers.

“Professional Cmake - A Practial Guide, by Craig Scott” also discourages the practice (Chapter 2.5).

At my company I’ve noticed this function repeated in many many code bases.

# In source builds cause a lot of problems and unneccessary complexity
function(prevent_in_source_builds)
    if (${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
        message(FATAL_ERROR "In-source builds are not allowed")
    endif()
endfunction()

I think it has enough merrit to be a policy, variable, or standard module.
Side note this function isn’t perfect. Since it still leaves some artifacts in the source dir…

3 Likes

Cc: @craig.scott

In order to avoid leaving artifacts in the source directory we need some kind of mark in the source tree that can be checked before reading CMakeLists.txt files. See CMake Issue 6672.