首页 > 解决方案 > CMakeLists 包含子目录中的头文件

问题描述

我第一次尝试使用 CMake,并且正在努力将头文件链接到我的主文件中。我的 cmake 目录如下所示:

Project
| CmakeLists.txt
| src
|| CMakeLists.txt
|| Main.cpp
| Libs
|| CMakeLists.txt
|| headers 
|||obstacle_detection.hpp
||source
|||obstacle_detection.cpp
|build
||"build files"

我想将文件headers夹中的文件链接到主文件,但我目前拥有的文件似乎不起作用。以下正确运行 CMake 命令,但无法使用该make命令编译,无法找到给定的头文件。我的 CMakeLists 文件如下:

项目:

cmake_minimum_required(VERSION 3.17)
project(Sensivision)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}") 
find_package(OpenCV REQUIRED)
find_package(realsense2 REQUIRED)
find_library(darknet REQUIRED)
add_subdirectory(libs)
add_subdirectory(src)
target_link_libraries(${PROJECT_NAME} obstacle_detection)

库:

add_library(
    obstacle_detection
    headers/obstacle_detection.hpp
    sources/obstacle_detection.cpp
)


target_link_directories(obstacle_detection PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")

源代码:

add_executable(${PROJECT_NAME} main.cpp)
target_link_libraries(${PROJECT_NAME} ${OpenCV_LIBS})
target_link_libraries(${PROJECT_NAME} ${realsense2_LIBRARY})

我在 main.cpp 中的包含是

include <obstacle_detection.hpp>

我也试过

include <headers/obstacle_detection.hpp>

include <obstacle_detection>

每个都给出错误:

obstacle_detection.hpp: no such file or directory 

我在将标题链接到主标题时做错了什么?

标签: c++cmake

解决方案


您尚未将任何包含目录添加到obstacle_detection库中。通过在调用中列出头文件add_library,这可能允许在 IDE 中显示头文件,但它对编译没有任何作用。您应该使用target_include_directoriesheaders目录添加为库的包含目录obstacle_detection。否则,它和其他消费目标将不知道该目录中的标头。

add_library(
    obstacle_detection
    headers/obstacle_detection.hpp
    sources/obstacle_detection.cpp
)

# Add this line. 
target_include_directories(obstacle_detection PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/headers)

# Not sure this line is necessary, as it doesn't appear you actually link anything...
target_link_directories(obstacle_detection PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")

您尚未在src目录中显示 CMake 代码,但请确保将库目标链接obstacle_detection到主目标,例如:

target_link_libraries(MyExeTarget PRIVATE obstacle_detection)

另外,因为这个头文件是本地的,所以最好使用引号来包含头文件:

#include "obstacle_detection.hpp"

推荐阅读