将一个项目链接到另一个CMAKE

时间:2019-06-12 11:50:53

标签: cmake

我正在构建一个包含很多子项目的项目。例如...

LibA (build as shared library)

LibB (depends on LibA & build as shared library)

AppB (depends on LinB)

目录结构(我想要的是)...

bin/
output/
src/libA/
src/libB/
src/appB/

每个子项目(LibA,LibB和AppB)都有自己的CMakeLists.txt文件。

我要..

1. Build LibA as shared library (I know how to do it)

2. Build LibB as shared library with linking of LibA (Don't Know how to do)
   Explanation: When I start building LibB, 
                LibA build first and 
                ready to link for LibB 
                when LibB ready to finish

3. Build AppB : If I start building AppB, 
                LibA build first and 
                LibB build after and
                both linked to AppB

现在,我知道经典方法,分别构建LibA和LibB并提供lib的路径并包含到AppB中。但我想像

一样一次构建它们
  Build LibA 
  Build LibB (if LibA is already build then ignore, else build LibA)
  Build AppB (if LibA, LibB are already build then ignore, else build them)

我想要的

  • 如何使用CMAKE实现这种行为?
  • 应该是跨平台的
  • 足够简单,可以包含更多子项目

1 个答案:

答案 0 :(得分:1)

这是一种解决方案。您可以使用顶级CMakeLists.txt文件将所有项目捆绑在一起。因此,在您的目录结构中,将其放置在此处:

bin/
output/
src/libA/
src/libB/
src/appB/
CMakeLists.txt    <--- Top-level CMakeLists.txt

您的顶级CMakeLists.txt文件(作为src目录的同级文件)可能如下所示:

cmake_minimum_required(VERSION 3.11)

# Add your dependencies in the order you want them to build.
add_subdirectory(src/libA)
add_subdirectory(src/libB)
add_subdirectory(src/appB)

每个src目录都有自己的CMakeLists.txt文件,下面是每个目录的示例。

您可以使用CMakeLists.txt中的src/libA文件将LibA设置为与CMake共享的库:

project(LibA_Project)
add_library(LibA SHARED sourceA.cpp  ... more sources here ...)

接下来,CMake将遍历src/libB目录以配置LibB。 src/libB/CMakeLists.txt文件如下所示:

project(LibB_Project)
# Create a shared library for LibB as well.
add_library(LibB SHARED sourceB.cpp  ... more sources here ...)

# Link LibA to LibB as a dependency.
target_link_libraries(LibB LibA)

最后,CMake将转到src/appB目录。这是CMakeLists.txt个文件:

project(AppB_Project)
# Create the executable AppB.
add_executable(AppB main.cpp ... more sources here ...)

# Link LibA and LibB to AppB as dependencies.
target_link_libraries(AppB LibA LibB)

如有必要,可以轻松地将该方法扩展为包括更多子项目(例如LibC,LibD,AppE等)。