cmake 项目仅构建一个特定的可执行文件(及其依赖项)

cmake project build only one specific executable (and its dependencies)

我有一个大致结构如下的 CMake 项目:

.
|-- library1
|   |-- CMakeLists.txt
|-- library2
|   |-- CMakeLists.txt
|-- executables
|   |-- CMakeLists.txt

我在名为 executables 的文件夹中生成了两个可执行文件。我想知道是否有可能只生成一个可执行文件及其依赖项而不是全部。我听说了一些关于 cmake --target 选项的信息,但我无法让它与 cmake/3.13.4.

一起工作

这里有几个潜在的问题。首先,典型的 CMake 工作流程将 build 文件夹作为顶层 CMake 文件的同级文件。所以你的文件层次结构应该是这样的:

.
|-- CMakeLists.txt
|-- library1
|   |-- CMakeLists.txt
|-- library2
|   |-- CMakeLists.txt
|-- executables
|   |-- CMakeLists.txt
|-- build    <------------ Run CMake commands from here.

这会将所有 CMake 生成的文件隔离到 build 文件夹中。其次,您必须注意 运行 CMake 构建阶段在正确的位置。我们可以 运行 build 文件夹中的所有内容,例如:

  1. build 目录生成构建系统、运行 cmake ..。第一步应该指向顶级 CMake 文件。

  2. 构建(或编译)一个特定的target,比如说它叫做MyExecutable1,运行这个:

    cmake --build . --target MyExecutable1
    

    来自 build 目录。您必须确保将 --build 标志指向 build 文件夹, 而不是 这次顶级 CMake 文件。此外,在此命令中指定的目标名称应与 add_executable() 中使用的目标名称相匹配, 而不是 项目名称或其他任何内容。

  3. 一如既往,在尝试 运行 CMake 时得到 errors/issues 时,它有助于清除缓存(删除 build/CMakeCache.txt),或者只删除 build 文件夹并重新开始。