如何处理 CMake 中的子目录依赖项?

How do I handle subdirectory dependencies in CMake?

我有一个项目需要 运行 一个应用程序在多个板上。为此,我有两个可执行文件共享 main.c,但使用不同的 board.c 编译。目录树如下:

CMakeLists.txt
src/
├─ board/
│  ├─ board_a/
│  │  ├─ board.c
|  |  ├─ CMakeLists.txt
│  ├─ board_b/
│  │  ├─ board.c
|  |  ├─ CMakeLists.txt
├─ app/
│  ├─ main.c
├─ lib/
│  ├─ somelib/
│  │  ├─ somelib.h
│  │  ├─ somelib.c

为了使根 CMakeLists.txt 更小且更易于维护,我为两个板创建了一个 CMakeLists.txt,并希望将每个板编译为主要的对象库可执行文件在根 CMakeLists.txtadd_subdirectory 上和 link 中。

我的问题是 board.c(以及 main.c)依赖于 somelib。如何将此依赖项添加到子目录 CMakeLists.txt?有没有一种方法可以在不硬编码 somelib 的路径的情况下做到这一点?我的感觉是我应该在 somelib 中创建一个 CMakeLists.txt,我觉得如果我从根 CMakeLists.txt 处理库 link 会很容易,但是我的混淆是 boardlib 相邻。我对 CMake 比较陌生,不确定如何最好地构建这些依赖项。

My problem is that board.c (as well as main.c) depends on somelib. How can I add this dependency to the subdirectory CMakeLists.txt? Is there a way I can do that without hard-coding a path to somelib? My feeling is that I should create a CMakeLists.txt in somelib, and I feel this would be easy if I were handling the library linking from the root CMakeLists.txt, but my confusion is that board is adjacent to lib. I'm relatively new to CMake and am not sure how to best structure these dependencies.

这非常简单,首先将每个 board_<X> 链接到 somelib 的目标。

# in each board_<X>/CMakeLists.txt

add_library(board_<X> OBJECT ...)
target_link_libraries(board_<X> PUBLIC proj::somelib)

然后为 somelib 创建目标:

# src/lib/somelib/CMakeLists.txt

add_library(somelib somelib.c)
add_library(proj::somelib ALIAS somelib)

target_include_directories(
  somelib PUBLIC "$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>")

只要 top-level CMakeLists.txt 通过 add_subdirectory 包含这些子目录(多级即可),其他目标就可以 #include <somelib.h> 并且 CMake 将处理链接。