首页 > 解决方案 > 使用 CMake FetchContent 模块解决后无法链接静态依赖项/库

问题描述

下面的一段代码不起作用。我想使用 解决名为dependency1 的依赖项FetchContent,它是一个静态库并链接到我的目标可执行文件。请注意,静态依赖项是 svn 中的 CMake 项目。

注意 FetchContent 在编译时成功地在 SOURCE_DIR 中执行 svn checkout,但是当我尝试将可执行文件链接到以下在线错误时,它会给出错误target_link_libraries(App1, dependency1)

Cannot specify link libraries for target "App1," which is not built by this  project.

我将不胜感激任何帮助。

我的CMakeLists.txt

cmake_minimum_required(VERSION 3.12 FATAL_ERROR)

project(App1)

include(FetchContent)

message("fetching dependency1")
FetchContent_Declare(
  dependency1
  SVN_REPOSITORY http://............/Dependency1
)

FetchContent_GetProperties(dependency1)

if(NOT dependency1_POPULATED)
  FetchContent_Populate(dependency1)
  add_subdirectory(${dependency1_SOURCE_DIR} ${dependency1_BINARY_DIR})
endif()

add_executable (App1 "App1.cpp" "App1.h")

link_directories(${dependency1_BINARY_DIR})

target_link_libraries(App1 dependency1)

感谢 Tsyvarev 解决了上述问题。我在 targer_link_libraries 中错误地使用了一个额外的逗号。

但是现在当我尝试构建它时无法找到静态库,即“libDependency1.a”

Scanning dependencies of target App1
[ 25%] Building CXX object App1/CMakeFiles/App1.dir/App1.cpp.o
[ 50%] Linking CXX executable App1
/usr/bin/ld: cannot find -ldependency1
collect2: ld returned 1 exit status
make[2]: *** [App1/App1] Error 1
make[1]: *** [App1/CMakeFiles/App1.dir/all] Error 2
make: *** [all] Error 2

我添加了 link_directories(${dependency1_BINARY_DIR}) 但它仍然没有解决问题。

我以某种方式能够解决问题,但无法完全理解事情是如何运作的。

如果我在 target_link_libraries 中使用 Dependency1 而不是 dependency1,则问题得到解决。

target_link_libraries(App1 dependency1) --- Does not work
 target_link_libraries(App1 dependency1)  --- Works

在 FetchContent 声明中,我将名称传递为“dependency1”,因为我记得“Dependency1”之前没有工作。请注意,我的依赖项的名称是 Dependency1 (with capital D) 。在 target_link_libraries 中,我认为它应该采用我传递给 FetchContent 声明的名称,但它非常奇怪。

标签: cmake

解决方案


推荐阅读