为cmake添加make install自定义命令

CMake生成的Makefile里,竟然是没有uninstall的。 尽管在大部分场合都没问题,但有时候还是比较麻烦。

make uninstall

一般的解决方案是,执行以下命令:

xargs rm < install_manifest.txt

当然,这需要先执行make install,以生成install_manifest.txt文件。 如果这个文件丢了,只能再安装一次,然后再卸载。

当然,可以通过添加自定义命令,来复刻这个configure时代的常见功能。

# make uninstall
add_custom_target("uninstall" COMMENT "Uninstall installed files")
add_custom_command(
    TARGET "uninstall"
    POST_BUILD
    COMMENT "Uninstall files with install_manifest.txt"
    COMMAND xargs rm -vf < install_manifest.txt || echo Nothing in
            install_manifest.txt to be uninstalled!
)

执行效果

根据一个Demo项目cmake-cpack-demo,演示uninstall的执行效果。

$ git clone https://github.com/yanqd0/cmake-cpack-demo.git
...
$ cmake . && make
...

$ sudo make install
[ 50%] Built target greet
[100%] Built target hello
Install the project...
-- Install configuration: "Release"
-- Installing: /usr/local/lib/libgreet.so
-- Installing: /usr/local/bin/hello
-- Set runtime path of "/usr/local/bin/hello" to ""
-- Installing: /usr/local/include/greet.h

$ sudo make uninstall
Uninstall files with install_manifest.txt
removed '/usr/local/lib/libgreet.so'
removed '/usr/local/bin/hello'
removed '/usr/local/include/greet.h'
Built target uninstall

参考

其实都是孤写的。


相关笔记