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

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


当前回答

如果你跑了

cmake .

它将重新生成CMake文件。如果您将一个新文件添加到由*选择的源文件夹中,这是必需的。比如Cc。

虽然这本身不是“清理”,但它通过重新生成缓存来“清理”CMake文件。

其他回答

简单地发布rm CMakeCache.txt也适用于我。

我用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

你可以这样使用:

add_custom_target(clean-cmake-files
   COMMAND ${CMAKE_COMMAND} -P clean-all.cmake
)

// clean-all.cmake
set(cmake_generated ${CMAKE_BINARY_DIR}/CMakeCache.txt
                    ${CMAKE_BINARY_DIR}/cmake_install.cmake
                    ${CMAKE_BINARY_DIR}/Makefile
                    ${CMAKE_BINARY_DIR}/CMakeFiles
)

foreach(file ${cmake_generated})

  if (EXISTS ${file})
     file(REMOVE_RECURSE ${file})
  endif()

endforeach(file)

我通常创建一个“make clean-all”命令,在前面的例子中添加一个调用“make clean”:

add_custom_target(clean-all
   COMMAND ${CMAKE_BUILD_TOOL} clean
   COMMAND ${CMAKE_COMMAND} -P clean-all.cmake
)

不要尝试将“clean”目标添加为依赖项:

add_custom_target(clean-all
   COMMAND ${CMAKE_COMMAND} -P clean-all.cmake
   DEPENDS clean
)

因为“干净”在CMake中不是一个真正的目标,这是行不通的。

此外,你不应该使用这个“clean-cmake-files”作为任何东西的依赖:

add_custom_target(clean-all
   COMMAND ${CMAKE_BUILD_TOOL} clean
   DEPENDS clean-cmake-files
)

因为,如果你这样做,所有的CMake文件将在clean-all完成之前被擦除,make将抛出一个搜索“CMakeFiles/clean-all.dir/build.make”的错误。因此,在任何情况下,都不能在"anything"前面使用clean-all命令:

add_custom_target(clean-all
   COMMAND ${CMAKE_BUILD_TOOL} clean
   COMMAND ${CMAKE_COMMAND} -P clean-all.cmake
)

这也不行。

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

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

为了简化使用“源外”构建时的清理(即在构建目录中构建),我使用以下脚本:

$ cat ~/bin/cmake-clean-build
#!/bin/bash

if [ -d ../build ]; then
    cd ..
    rm -rf build
    mkdir build
    cd build
else
    echo "build directory DOES NOT exist"
fi

每次你需要清理时,你应该从build目录中获取这个脚本:

. cmake-clean-build