How to fix CMake generation is not allowed within the source directory

Problem

While building a CMake project, you see an error message such as

CMake Error at CMakeLists.txt:844 (message):
  CMake generation is not allowed within the source directory! Remove the
  CMakeCache.txt file and try again from another folder, e.g.: rm
  CMakeCache.txt mkdir cmake-make cd cmake-make cmake ..

Solution

This project wants you to create a separate build directory and run CMake from there. Here’s how you can do that:

  1. Create a new directory for the build files:

    mkdir build
    cd build
    
  2. Run CMake from the new directory:

cmake ..

Note that it’s cmake .., not cmake . since you want CMake to build the project from the parent directory.

If that didn’t work, you must remove the CMakeCache.txt file and try again:

rm CMakeCache.txt # if you are running from the root of the project
rm ../CMakeCache.txt # if you are running this from the build directory

Then, try running cmake .. again.