c++ - 链接 src/与 CMake 作为库#include'd 与一些 `libname/` 前缀

标签 c++ cmake linker include-path

对于我的研究项目,我正在建立一个项目 (coom) 来对数据结构上的一组算法进行基准测试。对于单元测试,我选择了 Bandit,它给我留下了一个如下所示的项目结构:

+ root
|-- CMakeLists.txt
|-+ external/
| \-- bandit/
|-+ src/
| |-- CMakeLists.txt
| |-- node.cpp
| \-- node.h 
\-+ test/
  |-- CMakeLists.txt
  |-- test.cpp
  \-- test_node.cpp

根据我使用其他语言的经验,这在我看来是一个标准的项目结构? test/文件夹包含 src/ 中逻辑的单元测试并且没有依赖项与源代码和测试代码混合,而是在 external/ 中.

我的测试文件想要看起来如下(删除了不相关的部分)
// test/test.cpp
#include <bandit/bandit.h>
(...)

#include "test_node.cpp"

int main(int argc, char* argv[]) {
  (...)
}
// test/test_node.cpp
#include <coom/node.h>
(...)

但我的问题是,当我尝试使用 cmake .. 进行编译时和随后的 Makefile ,他们无法在 src/ 中找到源代码我在哪里得到编译器错误:
fatal error: coom/node.h: No such file or directory. 

我希望 test/CMakeLists.txt应该看起来像下面这样:
# test/CMakeLists.txt
add_executable (test_unit test.cpp)
target_link_libraries(test_unit coom)

我不知道如何设置 CMakeLists.txtsrc/CMakeLists.txt以确保我得到上述预期的结果。目前它们看起来如下:
# CMakeLists.txt
cmake_minimum_required(VERSION 3.8)
project (coom VERSION 0.1)

# ============================================================================ #
# Dependencies
(...)

# ============================================================================ #
# COOM project
add_subdirectory (src)
add_subdirectory (test)
# src/CMakeLists.txt
# ============================================================================ #
# Link up files for the library
set(HEADERS
  node.h
)

set(SOURCES
  node.cpp
)

add_library(coom ${HEADERS} ${SOURCES})

我可以从其他项目中看到,可以链接 src/带有一些 libname/ 的目录前缀,但我无法从他们的 CMakeLists.txt 中辨别出归档我做错了什么。我看过写一个 coom.pc.in文件并提供 install -target,并尝试 set_target_propertiesFOLDER coomPREFIX coom ,但都没有工作。我可以破解 include_directory(../src)进入test/CMakeLists.txt能够通过 #include <node.cpp> 包含文件,但这尖叫着我做错了。

在这一点上,我非常担心,CMake 文档对我帮助很小。

最佳答案

您的 coom target 没有定义包含目录。您可以定义用于此目标的包含目录(使用 target_include_directories() ),并传播这些包含目录,以便它们对消费 test_unit 可见。目标(通过使用 PUBLIC ):

# src/CMakeLists.txt
# ============================================================================ #
# Link up files for the library
set(HEADERS
  node.h
)

set(SOURCES
  node.cpp
)

add_library(coom ${HEADERS} ${SOURCES})

target_include_directories(coom PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})

此外,node.h 的文件路径标题是 coom/src/node.h ,而不是 coom/node.h .但是,因为你现在有 coom/src作为公共(public)包含目录,您可以使用以下内容来包含 node.h测试文件中的 header :
#include <node.h>

关于c++ - 链接 src/与 CMake 作为库#include'd 与一些 `libname/` 前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61187600/

相关文章:

visual-studio - 项目属性未打开 - "There are no property pages for the selection"

c++ - 使用 ExternalProject_Add 的 CMake 链接错误 1

c - 静态链接 glibc,但使用 GCC 动态链接其他一些库

c - 32位Linux上 "_Jv_RegisterClasses"和 "clock_gettime"在哪里定义的?

c++ - Arduino 与 Visual C++ 串口通信

visual-studio-2010 - 将错误与boost,VS2010和CMake链接

c++ - 除了内存管理,QObject 的父对象还有什么用?

c++ - 是什么导致这些链接器错误? (Visual C++ LNK2005)

C++ 模板完全特化语法

c++ - 跨平台 C++ IDE?