解析正交模块的依赖关系

Resolving dependencies of orthogonal modules

本文关键字:依赖 关系 模块      更新时间:2023-10-16

我有一个由几个模块组成的项目,我想使用 CMake 的add_subdirectory函数:

Project
+ CMakeLists.txt
+ bin
+  (stuff that depends on lib/)
+ lib
module1
+ CMakeLists.txt
+ (cpp,hpp)
module2
+ CMakeLists.txt
+ (cpp,hpp)
module3
+ CMakeLists.txt
+ (cpp,hpp)
logging.cpp
logging.hpp

这些顶级模块彼此独立,但它们都依赖于日志记录模块。 当我将相关的顶级模块代码从根CMakeLists移动到特定的子目录中时,由于缺少日志记录模块,我无法使用make编译它们。

有没有办法将对日志记录模块的依赖性编程为顶级模块CMakeLists,还是在根目录中调用cmake时自动解析?

有没有办法将对日志记录模块的依赖性编程到顶级模块的 CMakeList 中......

是的,您可以在根 CMakeLists.txt 文件中为日志记录功能定义 CMake 库目标。

CMakeLists.txt

cmake_minimum_required(VERSION 3.16)
project(MyBigProject)
# Tell CMake to build a shared library for the 'logging' functionality.
add_library(LoggingLib SHARED
lib/logging.cpp
)
target_include_directories(LoggingLib PUBLIC ${CMAKE_SOURCE_DIR}/lib)
# Call add_subdirectory after defining the LoggingLib target.
add_subdirectory(lib/module1)
add_subdirectory(lib/module2)
add_subdirectory(lib/module3)
...

然后,只需将日志记录库目标链接到需要它的其他模块目标即可。例如:

lib/module1/CMakeLists.txt

project(MyModule1)
# Tell CMake to build a shared library for the 'Module1' functionality.
add_library(Module1Lib SHARED
...
)
# Link the LoggingLib target to your Module1 library target.
target_link_libraries(Module1Lib PRIVATE LoggingLib)

请注意,这假定您从项目的根目录运行 CMake。例如,如果直接在lib/module1/CMakeLists.txt上运行 CMake,它将无法访问CMakeLists.txt文件中定义的日志记录目标。