CMake 将库包含在另一个库中
CMake include library in another library
>我有一个给定的项目结构
.
├── 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")
可以解决这个问题。
相关文章:
- 在作为静态成员包含在另一个类中的类的构造函数中使用 cout
- 检查路径是否包含C++中的另一个路径
- C++ .h 包含从一个类传递到另一个类的类和.cpp
- CMake 将库包含在另一个库中
- 如何将包含另一个对象向量的对象保存到文件中,并使用C++中的二进制文件从文件中读回?
- 创建一个 const std::vector ,其中包含另一个 const std::vector 和其他值
- 包含来自另一个文件的函数会导致范围错误(openFoam)
- 如何为包含另一个类实例的数组制作常量 getter?
- 使用按位运算确定值是否包含另一个值
- C++将包含的库 (ref DLL) 从根目录更改为另一个位置
- 如何在我的 cmake 项目中包含另一个 cmake 项目的头文件?
- 继承一个类,该类继承另一个已包含的类
- 如何查找哪个标头在包含树中包含另一个标头
- 将 2 个链表中包含的相同值写入另一个链表
- 如何从另一个包含目录中的标头访问包含目录中的标头
- 如何将另一个项目中用 C 编写的源代码包含在我自己的项目中,C++在 Visual Studio 中
- 包含另一个实例的特征实例,该实例持有固定大小的特征对象
- 如何隐藏另一个包含的静态库的API
- 如何从文件中的类调用,以使用着色器显示在另一个包含gl代码的文件中(其中两个文件都在jni文件夹中)
- 如何在另一个包含对象的文件中创建一个函数并从 main 调用它