从子目录中CMake链接库

Tom*_*lla 7 c++ linker gcc cmake sfml

我想在我的项目中包含SFML源代码.我的目录布局如下:

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

从主要级别我首先添加SFML子目录然后再​​添加src.正如我看到构建日志,这产生了库:

sfml?system
sfml?window
sfml?network
sfml?graphics
sfml?audio
sfml?main
Run Code Online (Sandbox Code Playgroud)

现在我想将它们链接到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
)
Run Code Online (Sandbox Code Playgroud)

但我得到:

/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
Run Code Online (Sandbox Code Playgroud)

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

Com*_*sMS 10

这应该可以正常工作。

使用 Windows 上的 Visual Studio 生成器和 CMake 3.2 上的 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)
Run Code Online (Sandbox Code Playgroud)

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

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

的事项真正的唯一的事情就是add_subdirectory调用发生之前target_link_libraries,这样的CMake已经知道了sfml-system目标。

  • 在当前的 CMake 中,“add_subdirectory”调用(创建目标“sfml-system”)和“target_link_libraries”调用(链接到该目标)之间的顺序并不重要:即使您重新排序这些调用,CMake 仍然正确确定“sfml-system”是目标,而不是普通文件。然而,创建“foo”目标的“add_executable”调用和将该目标链接到其他目标的“target_link_libraries”调用之间的顺序确实很重要。恢复顺序后,CMake 将发出错误。 (3认同)