CMakeLists.txt用于C ++项目中的第三方C文件

时间:2018-04-27 01:37:40

标签: c++ c cmake

我的C ++项目doggo有一个用于第三方代码的doggo/external/目录。目前它包含gtest和CMakeLists.txt:

# Google gtest for unit testing.
add_subdirectory(gtest)
message("gtest include dir: ${gtest_SOURCE_DIR}")
include_directories(${gtest_SOURCE_DIR})

我的顶级doggo / CMakeLists.txt包含用于查找和构建第三方库的行add_subdirectory(external)。一切都像魅力一样 - 我可以用#include <gtest/gtest.h>包含gtest。现在,我想将randomkit C库添加到doggo/external/,如下所示:randomkit from numpy

如何在我的doggo/external/目录中构建randomkit? doggo/external/CMakeLists.txt应该是什么样的?

然后,我应该能够通过在extern "C" { ... }块(details here)中包含标头来包含用于我的x.cpp文件的C标头。

更新:如何在此处安装randomkit? 我已经包含了一个如上所述的CMakeLists.txt条目但是对于randomkit,目录看起来像,

external
├── CMakeLists.txt
├── gtest
│   └── ...
└── randomkit
    ├── CMakeLists.txt
    ├── distributions.c
    ├── distributions.h
    ├── randomkit.c
    └── randomkit.h

randomkit/CMakeLists.txt

project(randomkit)
file(GLOB SOURCES "*.c")
add_library(randomkit SHARED ${SOURCES})
INSTALL(
    DIRECTORY ${CMAKE_SOURCE_DIR}/
    DESTINATION "/usr/local/"
    #DESTINATION ""
    FILES_MATCHING PATTERN "*.h*")

(第二个DESTINATION评论显示我也试过了)

然而,当我为顶级项目doggo运行构建步骤时,我在尝试#include <randomkit/distributions.h>时遇到错误:

doggo/src/random_fooz.cpp:10:37: fatal error: randomkit/distributions.h: No such file or directory

更新2 :doggo / CMakeLists.txt:

project(doggo)
# Find and build third-party libraries
add_subdirectory(external)
# Add source dirs to the search path so cmake can find headers
include_directories(${CMAKE_SOURCE_DIR}/include/)
# Collect source files and build
file(GLOB_RECURSE doggo_srcs ${CMAKE_SOURCE_DIR}/src/*.cpp)
add_library(doggo ${doggo_srcs})
# Setup executables
set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/bin/)
add_subdirectory(exec)
# Tests
add_subdirectory(test)

1 个答案:

答案 0 :(得分:0)

randomkit/CMakeLists.txt写:

project(randomkit)
file(GLOB SOURCES "*.c")
add_library(randomkit SHARED ${SOURCES})
target_include_directories(randomkit PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
INSTALL(
    DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/
    DESTINATION "include"            # this a the subdirectory with ${CMAKE_INSTALL_PREFIX}
    FILES_MATCHING PATTERN "*.h*")

在主CMakeLists.txt中,您可以:

add_library(doggo ${doggo_srcs})
target_link_libraries(doggo PUBLIC randomkit)
target_include_directories(doggo PUBLIC ${CMAKE_SOURCE_DIR}/include/)

请勿使用include_directories

现在,因为randomkit目标具有带有正确包含目录的PUBLIC属性,所以在构建doggo库时将自动使用这些目录。同样,因为doggo库在其公共接口中包含目录和库,所以链接到doggo的可执行文件将自动链接到这些库,并找到它们的包含文件。

请注意,INSTALL中的randomkit/CMakeLists.txt命令仅在您实际运行安装目标时执行。构建时,必须在源树中找到包含文件。