Disabling in-source builds
In Chapter 1, First Steps with CMake, we talked about in-source builds, and how it is recommended to always specify the build path to be out-of-source. This not only allows for a cleaner build tree and a simpler .gitignore
file, but it also decreases the chances you'll accidentally overwrite or delete any source files.
To stop the build early you may use the following check:
# ch04/09-in-source/CMakeLists.txt
cmake_minimum_required(VERSION 3.20.0)
project(NoInSource CXX)
if(PROJECT_SOURCE_DIR STREQUAL PROJECT_BINARY_DIR)
message(FATAL_ERROR "In-source builds are not allowed")
endif()
message("Build successful!")
Notice however, that no matter what you do, it seems like CMake will still create a CMakeFiles/
directory and a CMakeCache.txt
file.
You might find online suggestions to use undocumented variables to make sure that the user can't write in the source directory under any circumstances. Relying on undocumented variables...