C++在Cmake项目中包含库

C++ include library in Cmake project

本文关键字:包含库 项目 Cmake C++      更新时间:2024-09-23

我正试图使用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

我希望在main.cpp中运行与在example.cpp中运行的代码相同的代码,但我一直无法使导入正常工作。我导航到构建文件夹,cmake ..成功运行,但"make"失败,并出现导入错误(include行出现致命错误,找不到头文件(。这是有道理的,因为我没想到同样的include行也能工作(我将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>,该行引用库的CMakeLists.txt创建的build目录中gen目录中的文件(https://github.com/siposcsaba89/socketcan-cpp/blob/master/CMakeLists.txt)。我的顶级包找不到它。

为了包含下载库中的头文件,您可以将以下内容添加到CMakeLists.txt文件中:

find_library(downloaded_lib
NAMES downloaded_lib
HINTS "path to downloaded lib file")
if(NOT downloaded_lib)
message(FATAL_ERROR "downloaded_lib not found!")
endif()
target_include_directories(${PROJECT_EXECUTABLE} PUBLIC "path to download_lib.h")
target_link_libraries(${PROJECT_EXECUTABLE} ${downloaded_lib})

除了库文件之外,这还包括头文件所在的目录。