你的绘图有点混乱,因为在 Lib2 之后有一个 CMakeLists.txt 不属于任何文件夹......无论如何:是MyPack
- 库 1 和库 2 ?
- Lib1/Lib2/Subproj1/Subproj2 ?
在第二种情况下:
顶层目录 CMakeLists.txt 让您可以访问可以在 SubProject1 和 SubProject2 中使用的 Lib1 和 Lib2 的目标,如果您有以下内容:
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) 意味着您需要创建一个配置文件并 install() 您的项目:
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/
希望有帮助