CMakeLists.txt如何添加uninstall,并且写一个cmake_uninstall.cmake的实例
时间: 2023-07-08 19:29:59 浏览: 137
CMakeLists.txt编写示例
首先,在CMakeLists.txt中添加以下内容:
```
configure_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake_uninstall.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake"
IMMEDIATE @ONLY)
add_custom_target(uninstall
"${CMAKE_COMMAND}" -P "${CMAKE_CURRENT_BINARY_DIR}/cmake_uninstall.cmake")
```
然后,创建一个名为`cmake_uninstall.cmake.in`的文件,文件内容如下:
```
if(NOT EXISTS "${CMAKE_INSTALL_PREFIX}/install_manifest.txt")
message(FATAL_ERROR "Cannot find install manifest: ${CMAKE_INSTALL_PREFIX}/install_manifest.txt")
endif()
file(READ "${CMAKE_INSTALL_PREFIX}/install_manifest.txt" files)
string(REPLACE "\n" ";" files "${files}")
foreach(file IN LISTS files)
message(STATUS "Deleting file: ${file}")
if(EXISTS "${file}")
file(REMOVE "${file}")
endif()
# Remove empty directories
get_filename_component(dir "${file}" DIRECTORY)
if(EXISTS "${dir}" AND IS_DIRECTORY "${dir}")
file(GLOB children "${dir}/*")
if(NOT children)
message(STATUS "Removing empty directory: ${dir}")
file(REMOVE_DIRECTORY "${dir}")
endif()
endif()
endforeach()
```
这个文件的作用是卸载之前安装的文件和目录。它首先检查`${CMAKE_INSTALL_PREFIX}/install_manifest.txt`文件是否存在,该文件包含了之前安装的所有文件和目录列表。然后,它逐行读取该文件,并尝试删除每个文件和目录。最后,它会删除空目录。
注意:`${CMAKE_INSTALL_PREFIX}`是CMake中的一个变量,表示安装目录的路径,默认为`/usr/local`。
当你想要卸载安装的文件时,只需在构建目录中运行以下命令:
```
make uninstall
```
这将执行`cmake_uninstall.cmake`脚本,删除之前安装的所有文件和目录。
阅读全文