gpt4 book ai didi

c++ - CMake:将静态库从子目录链接到另一个子目录中的可执行文件

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:10:35 24 4
gpt4 key购买 nike

我有一个项目同时使用了我自己的代码和需要编译的外部代码。我的文件树如下。

PROJECT_ROOT
|--CMakeLists.txt
|--src
|--CMakeLists.txt
|--B1.cpp
|--B1.h
|--B2.cpp
|--B2.h
|
|--ext
| |--CMakeLists.txt
| |--outside_module
| | |--CMakeLists.txt
| | |--A1.h
| | |--A1.cpp
|
|--exe
|--CMakeLists.txt
|--runnerA.cpp
|--runnerB.cpp

我在下面粘贴了我的 CMakeList.txt 文件的结构。我遇到的问题是我的 runnerA 可执行文件给我一堆 undefined reference 错误,指向 A1.h 和 A1.cpp 中定义的符号。然而,出于某种原因,CMake 在尝试链接到可执行文件 runnerA 时无法找到我的库 A

我包含了其余代码,因为它编译得很好。我能够毫无问题地构建可执行文件 runnerB。我推断 runnerB 可以工作,因为源文件在我的 src 文件夹中,它是我的 exe 文件夹的父文件夹,因此 B 库范围包括 exe

我怎样才能让 CMake 知道在哪里可以找到我的 A 库,以便它可以在将它链接到 src/中的 runnerA 时找到它exe?


PROJECT_ROOT

cmake_minimum_required(VERSION 2.8)
project(MyProject)

add_subdirectory(src)

PROJECT_ROOT/src

find_package(Module REQUIRED)

# CREATE LIBRARIES
add_library(
B
B1.cpp B1.h
B2.cpp B2.h
)

# GROUP LIBRARIES TOGETHER
set(
B_LIBS
B
${Module_LIBS}
)


# INCLUDE DIRECTORIES
set(
B_INCLUDES
.
${Module_INCLUDE_DIRS}
)

# ASSIGN INCLUDES TO LIBRARY
target_include_directories(
B PUBLIC
${B_INCLUDES}
)


add_subdirectory(ext)
add_subdirectory(exe)

PROJECT_ROOT/src/ext

add_subdirectory(outside_module)

PROJECT_ROOT/src/ext/outside_module

find_package(Boost COMPONENTS
filesystem
system
log
thread
REQUIRED)

# ADD DEFINITIONS
add_definitions(-DBOOST_LOG_DYN_LINK) # Necessary to compile A with log shared libraries (instead of static)

# DEFINE LIBRARY
add_library(
A
A1.cpp A2.h
)

# LINK LIBRARIES
set(
A_LIBS
A
${Boost_FILESYSTEM_LIBRARY}
${Boost_LOG_LIBRARY}
${Boost_SYSTEM_LIBRARY}
${Boost_THREAD_LIBRARY}
)

# INCLUDE DIRECTORIES
set(
A_INCLUDES
${Boost_INCLUDE_DIRS}
)

PROJECT_ROOT/src/exe

# DEFINE EXECUTABLES
add_executable(runnerB runnerB.cpp)
add_executable(runnerA runnerA.cpp)


##################
# LINK LIBRARIES
##################
target_link_libraries(
runnerB
${B_LIBS}
)

target_link_libraries(
runnerA
${A_LIBS}
)

target_include_directories(
runnerA PUBLIC
${A_INCLUDES}
)

# INSTALLATION
install(TARGETS runnerB DESTINATION bin/)
install(TARGETS runnerA DESTINATION bin/)

最佳答案

是的,您在嵌套的 CMakeLists.txt 中设置了 ${A_LIBS} 变量。解决方案是使用 set() command使用 PARENT_SCOPECACHE 关键字。

关于c++ - CMake:将静态库从子目录链接到另一个子目录中的可执行文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42266488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com