Search code examples
cmakedirectory-structurebuilding

After an in-source build, how to force CMake to build someplace else?


Suppose I have a project named foo, with sources under /foo/src. Also suppose that at some point in the past, someone ran cmake /foo/src, so there are build files there.

Now, I want to perform a build of foo, in /foo/build. But if I cd /foo/build; cmake /foo/src - it treats /foo/src as the build directory, and configures and generates that build files there rather than in the current directory.

Questions:

  1. What is the minimal set of files in /foo/src to delete in order for cmake to configure and generate build files in /foo/build?
  2. Can I force cmake to use /foo/build without deleting anything from /foo/src?

Solution

  • 1. A sufficient set of files to delete

    A sufficient, though perhaps not minimal, set of files to delete:

    CMakeCache.txt
    Makefile
    cmake_install.cmake
    CMakeFiles/
    

    and if you also have tests enabled, then

    CTestTestfile.cmake
    Testing/
    tests/CTestTestfile.cmake
    tests/Makefile
    tests/cmake_install.cmake
    tests/CMakeFiles/
    

    2. How to force a different build location without deletions:

    If you execute

    cmake -B /foo/build -S /foo/src
    

    (for non-ancient versions of CMake), CMake will ignore the previous build and build under /foo/build. You don't need it to be your current working directory when issuing this command.

    The second part of this answer can actually be found within this answer