Prevent CMake build directory from being instantiated in a source directory
Short version
Problem description: cmake .
(or cmake path
) can generate a build directory in the same directory as the source CMakeLists.txt, overwriting other source code in the process
Proposed solution: CMake will fail to generate a build directory if a CMakeLists.txt already exists in the directory.
Long version
As of CMake version 3.15.3
% cmake --help
Usage
cmake [options] <path-to-source>
cmake [options] <path-to-existing-build>
cmake [options] -S <path-to-source> -B <path-to-build>
To create a new build directory, I go cmake <path-to-source>
and it instantiates a new build directory in the current working directory.
To update a build directory, I go cmake <path-to-existing-build>
and it updates the build directory.
Now, say that I have two directories. One is my source directory containing my CMakeLists.txt, and the other is my build directory, currently uninitialised.
- In my build directory, I go
cmake path/to/source
and it initialises my build directory - In my build directory, I can now go
cmake .
and it updates my build directory - In my source directory, I can go
cmake path/to/build
and it updates my build directory
Now, say that I am in my build directory, but I see all the CMake output (from cmake path/to/build
) and think that I'm in my source directory. I say cmake .
. At this point, cmake generates a build directory in my current directory, possibly overwriting a bunch of source files in the process.
I can avoid this by making very sure I never run cmake .
, but it's actually quite a sensible thing to do if one is, say, using the generated XCode project for editing but interacting with the built files on the command line.
In contrast, I can't think of a scenario where it makes sense to generate a build directory in a directory containing a CMakeLists.txt file.
Proposed change: cmake will error rather than generate a build in the same directory as a CMakeLists.txt file
Consequences:
-
cmake .
in a build directory will rebuild the CMake build info (existing behaviour) -
cmake .
in a directory with a CMakeLists.txt will fail (new behaviour) -
cmake .
in a directory with neither CMakeLists.txt or existing CMake build info will fail (existing behaviour)