最近在研究vcpkg和cmake的集成如何自建port,发现必须要在项目的cmake支持export,网上的信息比较零散,很多讲不到点上,或者太绕了,当然自己绕的弯路也不少,这里做一次总结。
# 一个完整的library或许应该包含src、doc、example、test等
# 这里project_name应该就是真实lib名字,下面export、configure_file等操作对象都是此project_name
# 还有,这里可以指定library的版本,随后可以通过${PACKAGE_VERSION}获取
project(project_name VERSION 1.0.0)
# 指定当前目录下的源码生成library——常规操作
aux_source_directory(. DIR_SRCS)
add_library(${PROJECT_NAME} SHARED ${DIR_SRCS})
# 指定头文件scope
target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_SOURCE_DIR}/include)
# 写入库的版本信息
include(CMakePackageConfigHelpers)
write_basic_package_version_file(
${PROJECT_NAME}ConfigVersion.cmake
VERSION ${PACKAGE_VERSION}
COMPATIBILITY AnyNewerVersion)
# PUBLIC_HEADER是buildin变量,不是随便定义的
set_target_properties(${PROJECT_NAME} PROPERTIES PUBLIC_HEADER
${CMAKE_SOURCE_DIR}/include/smt_logger.h)
# 将库文件,可执行文件,头文件等安装到指定目录
install(TARGETS ${PROJECT_NAME}
EXPORT ${PROJECT_NAME}Targets
LIBRARY DESTINATION lib
ARCHIVE DESTINATION lib
RUNTIME DESTINATION bin
PUBLIC_HEADER DESTINATION include)
# 将库的相关信息输出为${PROJECT_NAME}Targets.cmake,供find_package查找用
install(EXPORT ${PROJECT_NAME}Targets
FILE ${PROJECT_NAME}Targets.cmake
NAMESPACE Leica::
DESTINATION lib/cmake/${PROJECT_NAME})
# 将项目内的${PROJECT_NAME}Config.cmake.in生成${PROJECT_NAME}Config.cmake
# xxxConfig.cmake.in内的语法可自行查找
configure_file(${PROJECT_NAME}Config.cmake.in ${PROJECT_NAME}Config.cmake @ONLY)
# 将cmake的config文件及configVersion文件拷贝到指定目录,便于find_package()寻找
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
DESTINATION lib/cmake/${PROJECT_NAME})
网友评论