Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: CMake SFML Private Linkage  (Read 1858 times)

0 Members and 1 Guest are viewing this topic.

unlight

  • Newbie
  • *
  • Posts: 33
    • View Profile
    • Email
CMake SFML Private Linkage
« on: January 19, 2020, 03:02:37 am »
Howdy pardners

Throughout my time using SFML I have built up a library of common utility classes that I like to include in all of my projects (as I am sure most of us have). I am using CMake to generate build files for my projects (Linux), which works great, but something bugs me that I dont understand and I am hoping someone here may be able to explain.

Consider the following minimised CMakeLists.txt example

cmake_minimum_required(VERSION 3.12)
project(my_lib)

# Set project paths.
set(EXE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/example)
set(INC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/include)
set(SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR}/src)

# Find SFML.
find_package(SFML 2.5 COMPONENTS graphics system window REQUIRED)

# Build library.
file(GLOB_RECURSE LIB_SRC ${SRC_DIR}/*.cpp)
add_library(${PROJECT_NAME} STATIC ${LIB_SRC})

# Set include directories publicly.
target_include_directories(${PROJECT_NAME} PUBLIC ${INC_DIR})

# Link library to SFML privately.
target_link_libraries(${PROJECT_NAME} PRIVATE sfml-graphics sfml-system sfml-window)

# Build test
add_executable(my_exe ${EXE_DIR}/Test.cpp)

# Link test to library
target_link_libraries(my_exe ${PROJECT_NAME})


This script does the following:
  • Finds SFML
  • Builds my llibrary
  • Links my llibrary to SFML
  • Builds my executable
  • Links my executable to my library

What bugs me here is that I link my library to SFML manually, but my executable also gets linked SFML automatically, despite the fact that I am using the PRIVATE keyword while linking my library to SFML. This happens regardless of whether my library and executable are defined in the same CMake script, or seperate scripts with the executable adding the library via the add_subdirectory command.

This logic doesn't hold in other similar situations, which leads me to believe it might have something to do with the SFML cmake config? Can anyone explain the logic to me?

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: CMake SFML Private Linkage
« Reply #1 on: January 19, 2020, 08:41:14 am »
Your library is built statically. Which means that it's not linked (a static lib is just an archive of compiled files), all its dependencies, public or private, will be linked to the final binary.

Change your library type to SHARED and SFML shouldn't be linked to your exe anymore.
Laurent Gomila - SFML developer

unlight

  • Newbie
  • *
  • Posts: 33
    • View Profile
    • Email
Re: CMake SFML Private Linkage
« Reply #2 on: January 19, 2020, 11:51:13 am »
Ah right, that's pretty fundamental C++. Thanks so much Laurent!

 

anything