如何使用CMake创建软件包

时间:2019-04-11 14:44:11

标签: c++ cmake cmake-modules

.
+-- MyPack
|   +-- Lib1
|   |   +-- include
|   |   |   +-- Lib1.h
|   |   +-- src
|   |   |   +-- Lib2.cpp
|   |   +-- CMakeLists.txt
|   +-- Lib2
|   |   +-- include
|   |   |   +-- Lib2.h
|   |   +-- src
|   |   |   +-- Lib2.cpp
|   |   +-- CMakeLists.txt
|   +-- CMakeLists.txt
+-- SubProject1
|   +-- CMakeLists.txt
+-- SubProject2
|   +-- CMakeLists.txt
+-- CMakeLists.txt

大家好。

我是CMake的新手,我正在尝试获取类似以下内容的东西。 考虑我的C ++项目的上述目录树:

我有一个目录(假设为“ MyPack”),其中包含几个子目录(Lib1,Lib2 ...),每个目录都代表我编写的C ++库。

如何设置所有内容,以便可以在其他子项目中编写find_package(MyPack)

每个子项目都是一个独立项目,并且不依赖于其他子项目,而仅依赖于“ MyPack”中的库。

1 个答案:

答案 0 :(得分:0)

您的绘图有点混乱,因为Lib2之后有一个不属于任何文件夹的CMakeLists.txt ... 无论如何:是 MyPack

  • Lib1和Lib2?
  • Lib1 / Lib2 / Subproj1 / Subproj2吗?

在第二种情况下:

顶层目录CMakeLists.txt允许您访问Lib1和Lib2的目标,如果您有这样的事情,可以在SubProject1和SubProject2中使用它们:

project(MyPack)
add_subdirectory(Lib1) # Building Lib1
add_subdirectory(Lib2) # Building Lib2
add_subdirectory(SubProject1) # you can use Lib1 & Lib2 targets here
add_subdirectory(SubProject2) # you can use Lib1 & Lib2 targets here

如果是第一种情况, MyPack 仅是Lib1和Lib2:

使用find_package(MyPack)意味着您需要创建一个Config文件并安装()您的项目:

project(MyPack)
add_subdirectory(Lib1)
add_subdirectory(Lib2)

在Lib1 / CMakeLists.txt中:

add_library(lib1 "")
add_library(MyPack::lib1 ALIAS lib1)
[...]
include(GNUInstallDirs)
install( 
  TARGET lib1
  EXPORT MyPackTargets
  ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
  )

在Lib2 / CMakeLists.txt中:

add_library(lib2 "")
add_library(MyPack::lib2 ALIAS lib2)
[...]
include(GNUInstallDirs)
install( 
  TARGET lib2
  EXPORT MyPackTargets
  ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
  )

现在,在导出MyPackTargets中具有lib1和lib2。您还必须安装该导出。

以上任何地方:

install(
  EXPORT MyPackTargets
  DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MyPack
  NAMESPACE MyPack::
  FILE MyPackTargets.cmake # Not sure if this is still needed
  )

include(CMakePackageConfigHelpers)
configure_package_config_file( 
  "Config.cmake.in" 
  "MyPackConfig.cmake"
  INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/MyPack
  PATH_VARS
    CMAKE_INSTALL_LIBDIR
  )

write_basic_package_version_file(
  ${CMAKE_CURRENT_BINARY_DIR}/MyPackConfigVersion.cmake
  VERSION 1.0.0
  COMPATIBILITY SameMajorVersion
  )

### Install Config and ConfigVersion files
install(
  FILES "${CMAKE_CURRENT_BINARY_DIR}/MyPackConfig.cmake"
        "${CMAKE_CURRENT_BINARY_DIR}/MyPackConfigVersion.cmake"
  DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/MyPack"
  )

使用以下命令创建文件Config.cmake.in:

@PACKAGE_INIT@
include( "${CMAKE_CURRENT_LIST_DIR}/MyPackTargets.cmake" )

现在,如果您构建并安装MyPack项目,则其他项目中的find_package(MyPack)应该找到它并导入您创建的目标。

以下是一些文档: https://cmake.org/cmake/help/latest/module/CMakePackageConfigHelpers.html

https://blog.kitware.com/cmake-superbuilds-git-submodules/

希望有帮助