【问题标题】:CMake link library from subdirectory子目录中的 CMake 链接库
【发布时间】:2015-07-13 21:12:01
【问题描述】:

我正在尝试在我的项目中包含 SFML 源。我的目录布局如下:

main
  SFML (subtree synced with the official git repo)
  src
    <various modules>
    General (here lies the binary)

从主层我先添加 SFML 子目录,然后再添加 src。正如我在查看构建日志时看到的,这会生成库:

sfml‑system
sfml‑window
sfml‑network
sfml‑graphics
sfml‑audio
sfml‑main

现在我想将它们链接到 General 目录中的二进制文件,如下所示:

add_executable(main ${main_SRCS})
target_link_libraries (main
  sfml‑system
  sfml‑window
  sfml‑network
  sfml‑graphics
  sfml‑audio
  sfml‑main
  # Other stuff here
)

但我明白了:

/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lsfml‑system
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lsfml‑window
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lsfml‑network
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lsfml‑graphics
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lsfml‑audio
/usr/lib/gcc/x86_64-pc-linux-gnu/4.9.2/../../../../x86_64-pc-linux-gnu/bin/ld: cannot find -lsfml‑main

为什么 CMake 尝试使用系统库而不是它刚刚构建的那些,我该如何解决这个问题?

【问题讨论】:

  • 这些库是同一个 CMake 项目的目标吗?如果是这样,sfml‑system 等是目标的实际名称吗?
  • 顶级 CMakeLists 会:add_subdirectory(SFML) add_subdirectory(src) 我可以在构建日志中看到库名称:Linking CXX shared library ../../../lib/libsfml-graphics.so 等。
  • @BaummitAugen 我刚刚意识到 SFML 子目录定义了它自己的项目。我想这回答了你的问题并以某种方式改变了我的事情?
  • 如果sfml-system 不是当前 CMake 文件中的已知目标,您显然不能说 “链接到该目标!”。不过,您可以添加其他链接目录(即在其中搜索库的目录),请参见例如cmake.org/pipermail/cmake/2011-May/044295.html
  • @BaummitAugen 我不知道为什么你的链接说不使用link_directories,但这个问题的一个简单答案是“使用link_directories(&lt;location where library have been built&gt;”。 OP 应该将路径表示为${CMAKE_BUILD_DIR}/buildSubDirectory

标签: c++ gcc linker cmake sfml


【解决方案1】:

这应该可以工作。

在 CMake 3.2 上使用 Windows 上的 Visual Studio 生成器和 Linux 上的 Makefile 生成器尝试了以下操作:

project(test)

cmake_minimum_required(VERSION 2.8)

add_subdirectory(SFML-2.2)

add_executable(foo bar.cpp)
target_link_libraries(foo sfml-system)

SFML 构建正确,foo 正确链接到 sfml-system

您从另一个子目录构建可执行文件的事实不应该在这里产生影响。

真正重要的是add_subdirectory 调用发生在target_link_libraries 之前,因此CMake 已经知道sfml-system 目标。

【讨论】:

  • 您的答案是正确的,但由于某种原因在我的项目中不起作用(但是在虚拟项目中起作用)。出于这个原因,我选择它作为接受的答案。
  • 在当前的 CMake 中,add_subdirectory 调用(创建目标 sfml-system)和 target_link_libraries 调用(将 目标链接)之间的顺序无关紧要:即使您对这些调用重新排序,CMake 仍然可以正确确定 sfml-system 是一个目标,而不是一个普通文件。但是,add_executable 调用(创建 foo 目标)和 target_link_libraries 调用(将这个目标 链接到 其他目标)之间的顺序确实很重要。恢复顺序后,CMake 将发出错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-21
相关资源
最近更新 更多