CMakeLists包括子目录中的头文件



我第一次尝试使用CMake,并且很难将头文件链接到我的main中。我的cmake目录如下:

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

我想将headers文件夹中的文件链接到main,但我目前拥有的似乎不起作用。以下命令正确运行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)

Libs:

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

target_link_directories(obstacle_detection PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")

src:

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 

我错误地将页眉链接到主标题了吗?

您尚未向obstacle_detection库添加任何include目录。通过在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"

您可以使用target_include_directories在标头所在的位置添加文件夹,并在需要的位置添加#include <header.hpp>。例如:

libs cmake:
add_library(
obstacle_detection
headers/obstacle_detection.hpp
sources/obstacle_detection.cpp
)
target_include_directories(obstacle_detection PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}")
cpp:
#include <headers/obstacle_detection.hpp>

最新更新