首页 > 解决方案 > 具有多个组件的基本项目设置

问题描述

建立具有多个独立组件的项目的最佳方法是什么?

我的项目没有顶级 CMakeLists 文件,它由多个组件组成。其中一些可以独立构建,而另一些则依赖于其他组件。例如,组件 A 和 B 可以自己构建和使用(并且可能包含几个单独的目标),而组件 C 需要 A 和 B 来构建。

项目布局:

    ├───component_A
    │       CMakeLists.txt
    │       main.cpp
    │
    ├───component_B
    │       CMakeLists.txt
    │       main.cpp
    │
    └───component_C
             CMakeLists.txt
             main.cpp

我可以看到 3 种可能性,但它们似乎都不高效或可行:

  1. 使用 add_subdirectory(component_A CMAKE_BINARY_DIR/componentA)。

  2. ExternalProject_Add() 似乎太有限,无法处理大量组件

  3. 将每个组件视为一个包并使用 find_package 包含它们。在这种情况下,配置、安装等如何工作?

标签: cmake

解决方案


一种直接的解决方案是创建一个带有一些 CMake 的顶级 CMake options,让您可以控制整个项目中包含的内容。这些选项将填充并可以在 CMake GUI 中进行更改,但如果cmake从命令行运行,也可以对其进行控制。以下是适合您情况的简单顶级 CMake 文件的样子:

cmake_minimum_required(VERSION 3.11)

project(TopLevelProject)

# Define options to easily turn components ON or OFF.
option(ENABLE_COMPONENT_A "Option to include component A" ON)
option(ENABLE_COMPONENT_B "Option to include component B" OFF)
option(ENABLE_COMPONENT_C "Option to include component C" OFF)

# Determine which components are included and built by default in ALL_BUILD.
if(ENABLE_COMPONENT_C)
    # Need all three components in this case.
    add_subdirectory(component_A)
    add_subdirectory(component_B)
    add_subdirectory(component_C)
else()
    if(ENABLE_COMPONENT_A)
        add_subdirectory(component_A)
    endif()
    if(ENABLE_COMPONENT_B)
        add_subdirectory(component_B)
    endif()
endif()

在这个例子中,只有选项 A 是ON,所以只有组件 A 将包含在生成的构建系统中。即使您包含所有组件,您仍然可以在生成构建系统后选择单独构建哪些项目(或目标)。


推荐阅读