您可以使用for 的配置模式,find_package
允许您的模块向其用户(根项目)公开一些内部属性。
如果您的每个模块都提供库目标,您可以使用包含 Boost 版本的属性公开该目标,并在特殊的COMPATIBLE_INTERFACE_STRING属性中列出该属性。
您的根项目将通过find_package()
调用包含模块并将读取这些属性。当它将尝试链接此类模块提供的库时,CMake 将自动执行版本兼容性:
modA/CMakeLists.txt:
...
find_package(Boost)
add_library(modA_lib ...)
... # Link modA_lib with Boost
# Install modA_lib target and exports it for use in other project.
install(TARGETS modA_lib EXPORT modA_lib)
# Configured -config file is shown below
configure(modA-config.cmake.in modA-config.cmake)
install(EXPORT modA_lib
DESTINATION share/cmake/modA)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/modA-config.cmake
DESTINATION share/cmake/modA)
modA/modA-config.cmake.in:
include(@CMAKE_INSTALL_PREFIX@/share/cmake/modA/modA_lib.cmake) # Include file described library target
# Expose linked version of Boost via target's property.
set_property(TARGET modA_lib PROPERTY INTERFACE_BOOST_VERSION @Boost_VERSION@)
# Mark this property as compatibility requirement
set_property(TARGET modA_lib PROPERTY APPEND COMPATIBLE_INTERFACE_STRING BOOST_VERSION)
(modB以类似的方式实现)
根/CMakeLists.txt:
find_package(modA) # This imports target modA_lib
find_package(modB) # This imports target modB_lib
add_executable(root_exe <...>)
# Boost version check will be performed here
target_link_libraries(root_exe modA_lib modB_lib)
此外,在根项目中创建的可执行文件可以通过设置适当的属性来请求特定的 Boost 版本:
add_executable(root_exe <...>)
set_property(TARGET root_exe PROPERTY BOOST_VERSION <...>)
在这种情况下,将禁止(通过 CMake)其依赖项将 Boost 库与其他版本一起使用。
更多信息和使用示例请参见 CMake 构建系统描述。