正如make clean删除makefile生成的所有文件一样,我想对CMake做同样的事情。我经常发现自己手动地在目录中删除像cmake_install这样的文件。cmake和CMakeCache.txt,以及CMakeFiles文件夹。

是否有像cmake clean这样的命令来自动删除所有这些文件?理想情况下,这应该遵循当前目录的CMakeLists.txt文件中定义的递归结构。


当前回答

试着使用: cmake——clean-first path-of-CMakeLists.txt-file -B output-dir

-clean-first:先建造目标,然后再建造。 (只清洁,使用-目标清洁。)

其他回答

也许它有点过时,但由于这是你谷歌cmake clean时的第一个热门,我将添加这个:

因为您可以使用指定的目标在生成目录中启动生成

Cmake——构建。——目标xyz

你当然可以跑

Cmake——构建。——目标清洁

在生成的构建文件中运行干净目标。

CMake 3。X

CMake 3.0及以上版本提供了一个“干净”的目标。这将删除任何工件,如目标文件、库文件、可执行文件、生成文件等。

cmake --build C:/foo/build/ --target clean

您还可以清理构建,然后运行构建。在1命令。

cmake --build C:/foo/build --clean-first

但是,这不会清理CMakeCache.txt或相关的CMakeFiles/目录。你可能想这么做。你只需要删除构建文件夹。

# Just delete the build folder
rm C:/foo/build -rf

# You can also just let git delete the build folder as well
git clean -d -f -x

CMake 3.24

现在在CMake 3.24中,你可以执行一个新的构建树配置。这将删除任何现有的CMakeCache.txt文件和相关的CMakeFiles/目录,并从头开始重新创建它们。

一般情况下,你需要这样做:

你想清除CMakeCache.txt中的缓存变量 您希望更改编译器 任何与CMake缓存相关的其他操作

cmake -B C:/foo/build --fresh

为此,我使用以下shell脚本:

#!/bin/bash

for fld in $(find -name "CMakeLists.txt" -printf '%h ')
do
    for cmakefile in CMakeCache.txt cmake_install.cmake CTestTestfile.cmake CMakeFiles Makefile
    do
        rm -rfv $fld/$cmakefile
    done
done

如果您使用的是Windows,则使用Cygwin来执行此脚本。

我同意外部构建是最好的答案。但是当你必须在源代码内构建的时候,我写了一个Python脚本,可以在这里使用,它:

运行“make clean” 在顶级目录中删除特定的cmake生成的文件,例如CMakeCache.txt 对于每个包含CMakeFiles目录的子目录,它会删除CMakeFiles, Makefile, cmake_install.cmake。 删除所有空子目录。

我用zsxwing的答案成功解决了以下问题:

我有在多个主机上构建的源代码(在Raspberry Pi Linux板上,在VMware Linux虚拟机上,等等)。

我有一个Bash脚本,根据机器的主机名创建临时目录,就像这样:

# Get hostname to use as part of directory names
HOST_NAME=`uname -n`

# Create a temporary directory for cmake files so they don't
# end up all mixed up with the source.

TMP_DIR="cmake.tmp.$HOSTNAME"

if [ ! -e $TMP_DIR ] ; then
  echo "Creating directory for cmake tmp files : $TMP_DIR"
  mkdir $TMP_DIR
else
  echo "Reusing cmake tmp dir : $TMP_DIR"
fi

# Create makefiles with CMake
#
# Note: switch to the temporary dir and build parent 
#       which is a way of making cmake tmp files stay
#       out of the way.
#
# Note 2: to clean up cmake files, it is OK to
#        "rm -rf" the temporary directories

echo
echo Creating Makefiles with cmake ...

cd $TMP_DIR

cmake ..

# Run makefile (in temporary directory)

echo
echo Starting build ...

make