正如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官方常见问题解答说明:

Some build trees created with GNU autotools have a "make distclean" target that cleans the build and also removes Makefiles and other parts of the generated build system. CMake does not generate a "make distclean" target because CMakeLists.txt files can run scripts and arbitrary commands; CMake has no way of tracking exactly which files are generated as part of running CMake. Providing a distclean target would give users the false impression that it would work as expected. (CMake does generate a "make clean" target to remove files generated by the compiler and linker.) A "make distclean" target is only necessary if the user performs an in-source build. CMake supports in-source builds, but we strongly encourage users to adopt the notion of an out-of-source build. Using a build tree that is separate from the source tree will prevent CMake from generating any files in the source tree. Because CMake does not change the source tree, there is no need for a distclean target. One can start a fresh build by deleting the build tree or creating a separate build tree.

如果您有自定义定义,并希望在清理之前保存它们,请在构建目录中运行以下命令:

sed -ne '/variable specified on the command line/{n;s/.*/-D \0 \\/;p}' CMakeCache.txt

然后创建一个新的构建目录(或删除旧的构建目录并重新创建它),最后使用上面脚本获得的参数运行cmake。

当然,外部构建是Unix makefile的首选方法,但如果您使用的是其他生成器,如Eclipse CDT,它更喜欢您构建内源。在这种情况下,您需要手动清除CMake文件。试试这个:

find . -name 'CMakeCache.txt' -o -name '*.cmake' -o -name 'Makefile' -o -name 'CMakeFiles' -exec rm -rf {} +

或者,如果你已经通过shop -s globstar启用了globstar,试试这个不那么恶心的方法:

rm -rf **/CMakeCache.txt **/*.cmake **/Makefile **/CMakeFiles

这是我用的。它被包装在一个函数中,它是跨平台的,它演示了如何找到匹配的文件名或文件夹名,以防你想做任何简单的调整。这个函数在我每次构建脚本时都运行,并且完美地满足了我的需求。

function(DELETE_CACHE)
    if(CMAKE_HOST_WIN32)
        execute_process(COMMAND cmd /c for /r %%i in (CMakeCache.*) do del "%%i" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
        execute_process(COMMAND cmd /c for /d /r %%i in (*CMakeFiles*) do rd /s /q "%%i" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
    else()
        execute_process(COMMAND find . -name "CMakeCache.*" -delete WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
        execute_process(COMMAND "rm -rf `find . -type d -name CMakeFiles`" WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR})
    endif()
endfunction()

有趣的是,这个问题得到了如此多的关注和复杂的解决方案,这确实表明了cmake没有一个干净的方法的痛苦。

好吧,你当然可以cd build_work来做你的工作,然后在你需要清理的时候做一个rm -rf *。然而,rm -rf *是一个危险的命令,因为许多人通常不知道他们在哪个目录中。

如果你cd .., rm -rf build_work,然后mkdir build_work,然后CD build_work,输入太多了。

所以一个好的解决方案是远离build文件夹,告诉cmake路径: 配置:cmake -B build_work 要构建:cmake—build build_work 安装方法:cmake—install build_work 清理:rm -rf build_work 重建build文件夹:你甚至不需要mkdir build_work,只需配置cmake -B build_work即可。