【发布时间】:2022-01-23 10:44:24
【问题描述】:
我正在尝试使用 CMake 将我下载的 C++ 库集成到一个新项目中。
我下载了库(“downloaded_library”),创建了build 文件夹,并在其中运行了cmake .. 和make。这些都成功运行,然后我导航到构建文件夹并运行 ./example 以运行库附带的示例文件。这也是成功的,所以我希望将它添加到另一个项目中。
我将此工作项目添加到以下目录结构的“库”文件夹中:
project
-libraries
-downloaded_library
-build
-include
-downloaded_lib
-downloaded_lib.h
-src
-examples
-example.cpp
-CMakeLists.txt
-src
-main.cpp
-build
-CMakeLists.txt
我希望在example.cpp 和main.cpp 中运行相同的代码,但我一直无法使导入工作。我导航到构建文件夹,cmake .. 成功运行,但“make”失败并出现导入错误(包含行上的致命错误,找不到头文件)。这是有道理的,因为我没想到相同的包含行可以工作(我将 example.cpp 复制并粘贴到 main.cpp),但我不知道该怎么做。
fatal error: downloaded_lib/downloaded_lib.h: No such file or directory
1 | #include "downloaded_lib/downloaded_lib.h"
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
在这种情况下,我的 CMakeLists.txt 应该包含什么,我的 #include 应该包含什么才能像在 example.cpp 中一样使用 main.cpp 中的这个库的内容?
编辑--- 为了简单起见,我更改了上面的包名称,但“downloaded_library”的存储库如下:https://github.com/siposcsaba89/socketcan-cpp。
我的顶级 CMakeLists.txt 如下所示:
# Minimum version of CMake required to build this project
cmake_minimum_required(VERSION 3.0)
# Name of the project
project(projectname)
# Add all the source files needed to build the executable
add_executable(${PROJECT_NAME} src/main.cpp)
add_subdirectory(libraries/downloaded_library)
# Link the executable and the library together
target_link_libraries(${PROJECT_NAME} downloaded_library)
编辑2--(这里我将使用原始包名,socketcan-cpp)。
顶级 CMakeLists.txt:
# Minimum version of CMake required to build this project
cmake_minimum_required(VERSION 3.0)
# Name of the project
project(socketcan_demo)
# Add all the source files needed to build the executable
add_executable(${PROJECT_NAME} src/main.cpp)
add_subdirectory("libraries/socketcan-cpp")
target_include_directories(${PROJECT_NAME} PUBLIC "libraries/socketcan-cpp/include")
运行make 时出现此错误:
fatal error: socketcan_cpp/socketcan_cpp_export.h: No such file or directory
4 | #include <socketcan_cpp/socketcan_cpp_export.h>
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
compilation terminated.
因此顶级 CMakeLists 能够找到位于 include 中的头文件,但该头文件包含以下行:#include <socketcan_cpp/socketcan_cpp_export.h>,它引用了由库创建的 build 目录内的 gen 目录中的文件CMakeLists.txt (https://github.com/siposcsaba89/socketcan-cpp/blob/master/CMakeLists.txt)。而且我的顶级包找不到它。
【问题讨论】:
-
target_link_libraries?
-
现在我的根 CMakeLists.txt 中有
target_link_libraries(${PROJECT_NAME} downloaded_library),但它似乎没有帮助。 -
您需要发布一个真正的 MRE,即。 一切重现您的问题。通常,当您遇到问题并且无法自己解决时,这是因为(部分)您无法正确定位问题。如果您的项目是开源的,请发布指向 git repo 或其他内容的链接。
-
好的,我更新了问题以包括我下载的存储库和顶级 CMakeLists.txt。这就是这个项目中包含的所有内容。
-
所以如果下载的库确实是 socketcan_cpp,我假设你正在做
target_link_libraries(${PROJECT_NAME}socketcan_cpp)` 而不是target_link_libraries(${PROJECT_NAME} downloaded_library)。这应该已经为您提供了所需的包含目录,请参阅github.com/siposcsaba89/socketcan-cpp/blob/… 顺便说一句:链接的 cmake 命令与#include <socketcan_cpp/socketcan_cpp_export.h>结合表明库的 git 必须克隆到目录socketcan_cpp,而不是其他名称的目录。