c++ - 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
我在将标题链接到主标题时做错了什么?
解决方案
您尚未将任何包含目录添加到obstacle_detection
库中。通过在调用中列出头文件add_library
,这可能允许在 IDE 中显示头文件,但它对编译没有任何作用。您应该使用target_include_directories
将headers
目录添加为库的包含目录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"
推荐阅读
- azure - 无法使用 OpenIDConnect 从 HttpContext 获取 AAD 的访问令牌
- python - 如何用可调用类装饰类方法?
- python - 文本框不会自动删除自己
- python - 找到最小的解决方案集,如果存在(两个乘数)
- json - 如何访问复杂 JSON 文件中的对象,如下所示?
- javascript - 如何将数组拆分为偶数长度的块?
- php - 试图获取非对象的属性“类别”
- excel - 如何将不同大小的行转换为一列
- r - 将带有坐标的自定义立方体/框绘制到更大的 plot3d / plot3drgl 图中 - R
- google-chrome - 在独立 Chrome PWA 中打开 target="_blank" 链接时出现重复请求