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

问题描述 投票:0回答:1

我是 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 'library1' in directory 'MyProject/Library1'

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

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

c++ cmake shared-libraries
1个回答
1
投票

此代码是错误的。

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_*
命令,在使用已在计算机上安装
pre-built
二进制文件的包管理器、SDK 等时非常有用。

在这种情况下不需要它,因为

library1
已经是您项目的一部分。为什么 CMake 需要
find
它创建/定义的东西?

© www.soinside.com 2019 - 2024. All rights reserved.