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

时间:2015-09-17 19:05:22

标签: c++ cmake

我的代码组织如下:

  • CPP
    • main.cpp(调用来自dataStructures/common/的代码)
    • CMakeLists.txt( topmost CMakeLists文件)
    • 构建
    • 共同
      • CMakeLists.txt(应负责构建通用共享库)
      • 包括
        • utils.h
      • SRC
        • utils.cpp
      • 构建
    • 数据结构
      • CMakeLists.txt(构建dataStructures共享库 - 依赖于公共库)
      • 包括
        • dsLinkedList.h
      • SRC
        • 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} )

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

CMakeLists 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})

dataStructures

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})

更新

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

和commitId:4b4f1d3d24b5d82f78da3cbffe423754d8c39ec0 on my git

1 个答案:

答案 0 :(得分:2)

你只是错过了一件简单的事: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

它完全符合您的需要。