CMake教程11-添加导出配置

CMake教程11-添加导出配置

EXPORT导出配置的作用是帮助项目复用,其他项目可以复用有导出配置的项目。

怎么进行导出配置呢?

第一步,更新install()命令,添加EXPORT信息

func/CMakeLists.txt中添加:

target_include_directories(myfunc
    INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>
    PRIVATE $<BUILD_INTERFACE:${CMAKE_CURRENT_BINARY_DIR}>
    $<INSTALL_INTERFACE:include>
    )


install(TARGETS myfunc
    DESTINATION lib
    EXPORT MyFuncTargets)

然后再添加到CMakeLists.txt内容为:

install(EXPORT MyFuncTargets
  FILE MyFuncTargets.cmake
  DESTINATION lib/cmake/MyFunc
)


include(CMakePackageConfigHelpers)
# generate the config file that is includes the exports
configure_package_config_file(${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in
    "${CMAKE_CURRENT_BINARY_DIR}/MyFuncConfig.cmake"
    INSTALL_DESTINATION "lib/cmake/MyFunc"
    NO_SET_AND_CHECK_MACRO
    NO_CHECK_REQUIRED_COMPONENTS_MACRO
    )
# generate the version file for the config file
write_basic_package_version_file(
    "${CMAKE_CURRENT_BINARY_DIR}/MyFuncConfigVersion.cmake"
    VERSION "${VERSION_MAJOR}.${VERSION_MINOR}"
    COMPATIBILITY AnyNewerVersion
)

# install the configuration file
install(FILES
    ${CMAKE_CURRENT_BINARY_DIR}/MyFuncConfig.cmake
    ${CMAKE_CURRENT_BINARY_DIR}/MyFuncConfigVersion.cmake
    DESTINATION lib/cmake/MyFunc
  )

export(EXPORT MyFuncTargets
    FILE "${CMAKE_CURRENT_BINARY_DIR}/MyFuncTargets.cmake"
    )


在项目根目录新建Config.cmake.in文件,内容为:

@PACKAGE_INIT@

include ( "${CMAKE_CURRENT_LIST_DIR}/MyFuncTargets.cmake" )

重新构建项目,打包后的文件目录结构大致如下:

./FirstProject--Linux
├── bin
│   └── first_app
├── include
│   ├── config.h
│   └── myfunc.h
└── lib
    ├── cmake
    │   └── MyFunc
    │       ├── MyFuncConfig.cmake
    │       ├── MyFuncConfigVersion.cmake
    │       ├── MyFuncTargets.cmake
    │       └── MyFuncTargets-noconfig.cmake
    └── libmyfunc.so

导出就应该有导入,我们可以通过导入来使用被导出的库

导出后的库使用方法如下:

find_package(MyFuncTargets REQUIRED)
target_link_libraries(main MyFuncTargets)

# 支持调试版本与正式版本同时导入
find_library(math_REL NAMES m)
find_library(math_DBG NAMES md)
add_library(math STATIC IMPORTED GLOBAL)
set_target_properties(math PROPERTIES
  IMPORTED_LOCATION "${math_REL}"
  IMPORTED_LOCATION_DEBUG "${math_DBG}"
  IMPORTED_CONFIGURATIONS "RELEASE;DEBUG"
)
add_executable(myexe src1.c src2.c)
target_link_libraries(myexe PRIVATE math)


转载本文时请注明出处及本文链接地址CMake教程11-添加导出配置

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注