标签 cmake引用三方库 下的文章

CMake: 引入三方库及打包当前项目


前述

这里整一个cmake引入三方库及导出安装包的示例代码。
引入三方库用的是

set(*_DIR "**")
find_package(*)
target_link_libraries(${PROJECT_NAME} PRIVATE *)

导出安装报用到的是

install(TARGETS ${PROJECT_NAME} 
    RUNTIME 
    DESTINATION bin
)

install(
    FILES
    $<TARGET_FILE:*>
    DESTINATION bin
)
include (InstallRequiredSystemLibraries)\
...此处为CPack配置...
include(CPack)

示例

test.zip
Git testMain
Git testLib

CPack文档地址

https://cmake.org/cmake/help/latest/manual/cpack-generators.7.html

代码

部分代码已注释,具体详解也写道对应的注释里了。

cmake_minimum_required(VERSION 3.5.0)
project(testMain VERSION 0.1.1 LANGUAGES C CXX)

# set(testLib_DIR "Y:\\thirdparty\\testLib\\cmake")   # 如果不是安装形式的第三方库需要设置对应目录
find_package(testLib REQUIRED)                      # 查找已安装的三方库

include_directories(include)                        # 添加头文件路径
file(GLOB FILES_SRC "src/*.cpp")                    # 添加当前目录下的源文件至FILES_SRC

add_executable(${PROJECT_NAME} "main.cpp" ${FILES_SRC})

target_link_libraries(${PROJECT_NAME} PRIVATE testLib)

add_custom_command(                                 # 将自定义构建规则添加到生成的构建系统
    TARGET ${PROJECT_NAME}  POST_BUILD 
    COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:testLib> $<TARGET_FILE_DIR:${PROJECT_NAME}>         # 复制testLib.dll文件到目标目录
    # COMMAND ${CMAKE_COMMAND} -E make_directory $<TARGET_FILE_DIR:${PROJECT_NAME}>/bin/                              # 创建bin目录存放三方dll
    # COMMAND ${CMAKE_COMMAND} -E copy_if_different $<TARGET_FILE:testLib> $<TARGET_FILE_DIR:${PROJECT_NAME}>/bin/    # 复制dll库到bin目录
)

# add_custom_target(                                  # 增加一个没有输出的目标(总会被构建)
#     CopyFile
#     VERBATIM
#     COMMAND_EXPAND_LISTS
#     COMMAND ${CMAKE_COMMAND} -E copy_if_different
#     $<TARGET_FILE:testLib> $<TARGET_FILE_DIR:${PROJECT_NAME}>
# )

install(TARGETS ${PROJECT_NAME} 
    RUNTIME 
    DESTINATION bin                                 # 指定安装目录
)

install(
    FILES
    $<TARGET_FILE:testLib>
    DESTINATION bin                                 # 指定文件复制目录
)

############################## 打包 ##############################
include (InstallRequiredSystemLibraries)
# set(CPACK_GENERATOR ZIP)                            # 指定打包成ZIP
set(CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/License.txt")  #设置安装界面的License
set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "amd64")      #设置架构
set(CPACK_DEBIAN_PACKAGE_NAME "测试软件")           #设置程序名,就是程序安装后的名字
set(CPACK_PACKAGE_NAME "测试软件")                  #设置安装包的包名,打好的包将会是<packagename>-<version>-<sys>.deb,如果不设置,默认是工程名
set(CPACK_PACKAGE_VERSION "1.0.0")                  #设置版本号
set(CPACK_SYSTEM_NAME "win64")                      #系统名
SET(CPACK_PACKAGE_DESCRIPTION "这是一个测试软件 项目包")        #设置description
SET(CPACK_PACKAGE_CONTACT "root@bug-maker.com")     #设置联系方式
set(CPACK_DEBIAN_PACKAGE_MAINTAINER "猪在天上飞")   #设置维护人
# set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA "${CMAKE_SOURCE_DIR}/DEBIAN/postinst;${CMAKE_SOURCE_DIR}/DEBIAN/postrm;")  #设置包的安装脚本
include(CPack)

结果