Build Hygiene

Introduction

Include disable_in_source_builds.cmake in your CMakeLists.txt file to prohibit invocation of cmake in the project directory.

Rationale

The best practice for build systems is to put all build artifacts into a separate build directory — typically located at the root of the project tree.

That way, the source tree is kept clean of object files, executables, library archives, etc., making it easy to clean everything up by deleting the entire build directory. It is also easy to create a rule for your source code control system that prevents checking all the ephemeral build artefacts into the code repository.

This concept is now considered fundamental, and newer IDEs and build systems always enforce and never pollute the main source tree with any build artefacts.

Of course, CMake is happy to work with out-of-source builds, and indeed, every guide you will ever read tells you on page 1 how to make sure to do just that. However, unfortunately, CMake also allows in-source builds where the object files, etc., can end up in the same spots as the source files.

All modern CMake projects try to prevent that inadvertent use. This module does just that and is typically loaded very early in the CMakeLists.txt file. For example, if your CMake modules are in the cmake subdirectory you might have a line like:

include(cmake/disable_in_source_builds.cmake)

Now, if you try to invoke cmake and are not building out-of-source, the system will exit with a polite error message telling you exactly how to correct the situation.

Back to top