CMake:在构建过程中链接库?

1wnzp6jl  于 2023-10-20  发布在  其他
关注(0)|答案(1)|浏览(108)

我是CMake的新手,我试图链接在同一个项目中生成的库。(简化的)项目结构如下所示:

MyProject
├── CMakeLists.txt
├── Library1
│   └── CMakeLists.txt
│   └── include
│       └── foo.h
│       └── bar.h
│   └── src
│       └── foo.cpp
│       └── bar.cpp
├── Library2
│   └── CMakeLists.txt
│   └── include
│       └── baz.h
│   └── src
│       └── baz.cpp

CMakeLists.txt:

cmake_minimum_required (VERSION 3.17.0)
project(MyProject)

option(BUILD_SHARED_LIBS ON)

add_subdirectory(Library1)
add_subdirectory(Library2)

Library1/CMakeLists.txt:

project(Library1)

add_library(library1 
    src/foo.cpp 
    src/bar.cpp
)

target_include_directories(library1 PUBLIC
    ${CMAKE_SOURCE_DIR}/Library1/include
)

Library2/CMakeLists.txt:

project(Library2)

add_library(library2 
    src/baz.cpp
)

target_include_directories(library2 PUBLIC
    ${CMAKE_SOURCE_DIR}/Library1/include
    ${CMAKE_SOURCE_DIR}/Library2/include
)

find_library(LIB1 library1 HINTS ${CMAKE_SOURCE_DIR}/Library1)

target_link_libraries(library2 PUBLIC LIB1)

如果我运行cmake MyProject,我会得到这个错误:

CMake Error: The following variables are used in this project, but they are set to NOTFOUND. 
LIB1 
    linked by target 'library2' in directory 'MyProject/Library2'

--- Generating done
CMake Generate step failed. Build files cannot be regenerated correctly.

library1目标直到cmake --build MyProject之后才生成时,如何将library2链接到library1?或者这不是构建这个项目的正确方式?

kmynzznz

kmynzznz1#

这个代码是错误的。

find_library(LIB1 library1 HINTS ${CMAKE_SOURCE_DIR}/Library1)

target_link_libraries(library2 PUBLIC LIB1)

在你所展示的项目中,你不需要find任何库。它已经是你的一部分了。
要解决您的问题,只需链接库:

target_link_libraries(library2 PUBLIC library1)

TLDR解释何时使用find_*命令:
CMake提供了大量的find_*命令,这些命令在使用包管理器、SDK等时非常有用。在您的计算机上安装了pre-built二进制文件。
在这种情况下,它是不需要的,因为library1已经是项目的一部分。为什么CMake需要find它创建/定义的东西?

相关问题