首页 > 解决方案 > 链接到链接到另一个静态库的已构建静态库

问题描述

对不起,如果标题看起来有点复杂。基本思路如下:我有一个主 CMakeLists.txt 文件,其中添加了三个子目录。其中第一个是一个 CMakeLists.txt 文件,它会拉取一个 boost-cmake 版本。

FetchContent_Declare(boost-cmake
                     GIT_REPOSITORY https://github.com/ *****/boost-cmake
                     GIT_TAG master)

FetchContent_GetProperties(boost-cmake)

if(NOT boost-cmake_POPULATED)
  FetchContent_Populate(boost-cmake)
  add_subdirectory(${boost-cmake_SOURCE_DIR} ${boost-cmake_BINARY_DIR})
endif()

第二个创建一个与此链接的库。

add_library(program Program.cpp)
target_link_libraries(program ${Boost_LIBRARIES})

这会成功并生成一个 .lib 文件。话虽如此,它似乎包含 Program.cpp #includes 中包含的所有增强功能的符号

最后,当我尝试将 program.lib 库与可执行文件链接时:

include_directories(${CMAKE_SOURCE_DIR}/src)

add_executable(program_test Program_Test.cpp)

target_link_libraries(program_test PRIVATE program)

构建它会导致以下错误:

FAILED: test/CMakeFiles/program_test.dir/program_test.cpp.obj
C:\PROGRA~2\MICROS~1\2019\COMMUN~1\VC\Tools\MSVC\1421~1.277\bin\HostX64\x64\cl.exe  /nologo /TP  -I..\src /DWIN32 /D_WINDOWS /W3 /GR /EHsc /MDd /ZI /Ob0 /Od /RTC1 /JMC   -std:c++latest /showIncludes /Fotest\CMakeFiles\program_test.dir\program_test.cpp.obj /Fdtest\CMakeFiles\program_test.dir\ /FS -c ..\test\program_test.cpp
D:\Git\program\src\connection\program.hpp(5): fatal error C1083: Cannot open include file: 'boost/beast.hpp': No such file or directory

要求所有这样的嵌套依赖项是标准的吗?是否有任何解决方法可以确保所有的 boost 定义都包含在库中,从而只需要库本身?

值得一提的是,我尝试以与库中包含的相同方式包含 boost/beast.hpp 文件,但这似乎也不能解决问题,尽管无论如何这都不是一个更好的解决方案。

标签: cmake

解决方案


你没有链接错误,你有一个编译错误。

D:\Git\program\src\connection\program.hpp(5): fatal error C1083: Cannot open include file: 'boost/beast.hpp': No such file or directory

VisualStudio 编译器找不到boost/beast.hpp. 在CMakeLists.txt您共享的内容中,您没有告诉您的目标,program_test在哪里可以找到它的包含文件。就像您添加 atarget_link_libraries()以便 VisualStudio 链接器可以找到库一样,您需要添加 atarget_include_directories()以便 VisualStudio 编译器可以在您的Program_Test.cpp.


推荐阅读