如何使用 cmake 在子目录中构建库?

bra*_*ter 4 c++ cmake

我的代码是这样组织的:

  • cp
    • main.cpp(从dataStructures/和调用代码common/
    • CMakeLists.txt(最顶层的CMakeLists 文件)
    • 建造
    • 常见的
      • CMakeLists.txt(应该负责构建公共共享库)
      • 包括
        • 实用程序.h
      • 源文件
        • 实用程序.cpp
      • 建造
    • 数据结构
      • CMakeLists.txt(构建dataStructures共享库——依赖公共库)
      • 包括
        • dsLinkedList.h
      • 源文件
        • dsLinkedList.cpp
      • 建造

build\目录包含构建的目标。实际代码可以在这里看到:https : //github.com/brainydexter/PublicCode/tree/master/cpp

截至目前,每个子目录中的 CMakeLists.txt 都构建了自己的共享库。最顶层的 CMakeLists 文件然后引用这样的库和路径

最顶层的 CMakeLists.txt

cmake_minimum_required(VERSION 3.2.2)
project(cpp)

#For the shared library:
set ( PROJECT_LINK_LIBS libcppDS.dylib libcppCommon.dylib)
link_directories( dataStructures/build )
link_directories( common/build )

#Bring the headers, into the project
include_directories(common/include)
include_directories(dataStructures/include)

#Can manually add the sources using the set command as follows:
set(MAINEXEC main.cpp)

add_executable(testDS ${MAINEXEC})
target_link_libraries(testDS ${PROJECT_LINK_LIBS} )
Run Code Online (Sandbox Code Playgroud)

如果尚未构建它们,我如何更改最顶层的 CMakeLists.txt 以进入子目录(commondataStructures)并构建它们的目标,而无需手动构建各个库?

CMakeLists for common

cmake_minimum_required(VERSION 3.2.2)
project(cpp_common)
set(CMAKE_BUILD_TYPE Release)

#Bring the headers, such as Student.h into the project
include_directories(include)

#However, the file(GLOB...) allows for wildcard additions:
file(GLOB SOURCES "src/*.cpp")

#Generate the shared library from the sources
add_library(cppCommon SHARED ${SOURCES})
Run Code Online (Sandbox Code Playgroud)

数据结构

cmake_minimum_required(VERSION 3.2.2)
project(cpp_dataStructures)
set(CMAKE_BUILD_TYPE Release)

#For the shared library:
set ( PROJECT_LINK_LIBS libcppCommon.dylib )
link_directories( ../common/build )

#Bring the headers, such as Student.h into the project
include_directories(include)
include_directories(../common/include/)

#However, the file(GLOB...) allows for wildcard additions:
file(GLOB SOURCES "src/*.cpp")

#Generate the shared library from the sources
add_library(cppDS SHARED ${SOURCES})
Run Code Online (Sandbox Code Playgroud)

更新:

这个拉取请求帮助我理解了正确的方法:https : //github.com/brainydexter/PublicCode/pull/1

和 commitId: 4b4f1d3d24b5d82f78da3cbffe423754d8c39ec0在我的 git 上

ypn*_*nos 5

你只缺少一个简单的东西:add_subdirectory. 从文档:

add_subdirectory(source_dir [binary_dir] [EXCLUDE_FROM_ALL])

将子目录添加到构建中。source_dir 指定源 CMakeLists.txt 和代码文件所在的目录。如果它是一个相对路径,它将相对于当前目录进行评估(典型用法),但它也可能是一个绝对路径。binary_dir 指定放置输出文件的目录。如果它是相对路径,它将相对于当前输出目录进行评估,但它也可能是绝对路径。

http://www.cmake.org/cmake/help/v3.0/command/add_subdirectory.html

它完全符合您的需求。