How can I perform a clean operation using CMake?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Performing a clean operation using CMake is unfortunately not as straightforward as it is with certain other build systems as CMake itself does not have a built-in ‘clean’ command. However, it can be done manually or with certain makefile generators. Here are two methods:
1. Manual Removal: Delete the build directory created when CMake was first run. This ensures every build file is erased and next build will be completely fresh. For example, if you have a directory named ‘build’, use the command ‘rm -r build’ in a Unix-based system or ‘rmdir /S build’ in Windows.
2. Makefile Generators: If you’re using a Makefile generator (like Unix Makefiles), you can use the command ‘make clean’. Be aware, it just removes the files built (like .o files in case of GCC compiler), not the files generated by CMake (like Makefile, cmake_install.cmake and CMakeCache.txt). However, it will not work for all build systems (like Ninja or Visual Studio).
If you want to add a clean target to your CMake project, you can include something like this in your CMakeLists.txt:
“`
add_custom_target(clean-cmake-files
COMMAND ${CMAKE_COMMAND} -P clean-all.cmake
)
# In clean-all.cmake
file(REMOVE_RECURSE “${CMAKE_BINARY_DIR}/CMakeCache.txt”
“${CMAKE_BINARY_DIR}/CMakeFiles”
“${CMAKE_BINARY_DIR}/cmake_install.cmake” )
“`
This allows you to use command ‘make clean-cmake-files’ which will remove generated files by CMake only. This is only for Unix Makefiles. This could be adapted for other generators as well.
To perform a clean operation with CMake, you cannot use a direct command like `make clean` as CMake doesn’t natively support this functionality. However, you can manually delete the CMake build directory (usually called “build” or “bin”) to achieve a similar result. Alternatively, use a script that removes the directory and recreates it, or use the `add_custom_target()` function in your CMakeLists.txt file to create a custom clean command.