CMake 将库包含在另一个库中

CMake include library in another library

本文关键字:另一个 包含 CMake      更新时间:2023-10-16

>我有一个给定的项目结构

.
├── CMakeLists.txt
├── lib
│   ├── lodepng
│   │   ├── CMakeLists.txt
│   │   └── src
│   │       ├── lodepng.cpp
│   │       └── lodepng.h
│   └── pixel_reader
│       ├── CMakeLists.txt
│       └── src
│           ├── hello.cpp
│           └── hello.h
├── main.cpp

使用以下 CMakeList

./CMakeLists.txt

cmake_minimum_required(VERSION 3.17)
project(pov_system VERSION 1.0)
add_subdirectory(lib/lodepng)
add_subdirectory(lib/pixel_reader)
add_executable(pov_system main.cpp)
target_link_libraries(pixel_reader PRIVATE lodepng)
target_link_libraries(pov_system PRIVATE pixel_reader)

./lodepng/CMakeLists.txt

add_library(
lodepng
src/lodepng.cpp
src/lodepng.h
)
target_include_directories(lodepng PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/src")

./pixel_reader/CMakeLists.txt

add_library(
pixel_reader SHARED
src/hello.cpp
src/hello.h
)
target_include_directories(pixel_reader PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/src")

正如人们所看到的,我尝试将"lodepng"库链接到"pixel_reader"库,并将"lodepng.h"包含在"hello.h"文件中。 但是目前我在尝试构建项目时收到以下错误。

[build] <path-to-project>/pov_system/lib/pixel_reader/src/hello.h:2:10: fatal error: lodepng.h: No such file or directory
[build]     2 | #include "lodepng.h"
[build]       |          ^~~~~~~~~~~
[build] compilation terminated.

问题

为什么我的代码找不到"lodepng.h"文件,或者(更重要的是(从一个库链接到另一个库是一种好习惯吗?

也许有两个非常简单的问题,但刚刚开始潜入CMake,编译等世界......我真的很感谢你的帮助。

为什么我的代码找不到"lodepng.h"文件或(甚至更重要(

因为您可能没有给它正确的路径。解决此问题的一种方法是在hello.h中给出确切的路径

#include "../../lodepng/src/lodepng.h

第二种方法是使用target_include_directories

target_include_directories(pixel_reader PUBLIC "../../lodepng/src/")

从一个库链接到另一个库是一种好的做法吗?

这取决于您的项目。如果库 A需要库 B,那么是的,在我看来没关系。

更重要的是,您在错误的位置(即根 CMakeLists( 文件中创建目标。必须在创建目标的目录中完成此操作。

./pixel_reader/CMakeLists.txt

# create target
add_library(
pixel_reader SHARED
src/hello.cpp
src/hello.h
)
target_link_libraries(pixel_reader PRIVATE lodepng) #link library where target is created
target_include_directories(pixel_reader PUBLIC "../../lodepng/src/")
target_include_directories(pixel_reader PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/src")

您的pixel_reader库目标可能需要 lodepng.h 标头来编译,因为它依赖于它。

类似的东西

target_include_directories(pixel_reader PUBLIC "PATH_TO_LODE_PNG_HEADER_DIRECTORY")

可以解决这个问题。