CMake link library from subdirectory

Tommalla picture Tommalla · May 4, 2015 · Viewed 15.7k times · Source

I am trying to include SFML sources in my project. My directories are laid out like this:

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

From the main level I am adding SFML subdirectory first and then src. As I've seen looking at the build log, this produces libraries:

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

Now I want to link them to my binary in the General directory like this:

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

But I get:

/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

Why does CMake try to use system libraries instead of those it just built and how do I fix this?

Answer

ComicSansMS picture ComicSansMS · May 5, 2015

This should just work.

Tried the following with Visual Studio generator on Windows and Makefile generator on Linux on CMake 3.2:

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 is built correctly and foo links correctly to sfml-system.

The fact that you build your executable from another subdirectory should not have an impact here.

The only thing that matters really is that the add_subdirectory call happens before the target_link_libraries, so that CMake already knows the sfml-system target.