CMake Uninstall

CMake does not provide a built-in uninstall command, but you can implement an uninstall process manually using the install_manifest.txt file generated during installation. Below are the steps to add and execute an uninstall target in your CMake project.

1. Create an uninstall Script

  • Create a file named cmake_uninstall.cmake.in in your project directory with the following content:

if(NOT EXISTS "@CMAKE_BINARY_DIR@/install_manifest.txt")
message(FATAL_ERROR "Cannot find install manifest: @CMAKE_BINARY_DIR@/install_manifest.txt")
endif()

file(READ "@CMAKE_BINARY_DIR@/install_manifest.txt" files)
string(REGEX REPLACE "\n" ";" files "${files}")

foreach(file ${files})
message(STATUS "Uninstalling $ENV{DESTDIR}${file}")
if(IS_SYMLINK "$ENV{DESTDIR}${file}" OR EXISTS "$ENV{DESTDIR}${file}")
execute_process(COMMAND "@CMAKE_COMMAND@" -E remove "$ENV{DESTDIR}${file}")
else()
message(STATUS "File $ENV{DESTDIR}${file} does not exist.")
endif()
endforeach()
 

2. Add Uninstall Target to CMakeLists.txt

  • Modify your CMakeLists.txt file to include the uninstall target:

if(NOT TARGET uninstall)
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
IMMEDIATE @ONLY
)
add_custom_target(uninstall
COMMAND ${CMAKE_COMMAND} -P ${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake
)
endif()
 

3. Execute the Uninstall Command

  • After building and installing your project, you can run the following command to uninstall:

sudo make uninstall
 

This will remove all files listed in the install_manifest.txt.

Best Practices

  • Always verify that the install_manifest.txt exists before running the uninstall process.

  • For UNIX systems, you can also directly use:

xargs rm < install_manifest.txt
 

to remove installed files.

By following these steps, you can safely implement and execute an uninstall process for your CMake-based projects.

posted @ 2025-12-06 18:19  z.seven  阅读(0)  评论(0)    收藏  举报