Search code examples
c++cmakesfml

CMake project building with SFML library


i can't understand how to build SFML-project using CMakeLists.txt file.
Help me, please, if you have time. Thank you!)

Details

I downloaded SFML library from official site (https://www.sfml-dev.org/index.php), moved it to my project root (see screenshots below), wrote C++-code using SFML and entered this cmake-command:

.../test_proj> cmake -G "Ninja" .

But in console output i got this:

CMake Warning at subdir_02/CMakeLists.txt:5 (find_package):
  By not providing "FindSFML.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "SFML", but
  CMake did not find one.

  Could not find a package configuration file provided by "SFML" with any of
  the following names:

    SFMLConfig.cmake
    sfml-config.cmake

  Add the installation prefix of "SFML" to CMAKE_PREFIX_PATH or set
  "SFML_DIR" to a directory containing one of the above files.  If "SFML"
  provides a separate development package or SDK, be sure it has been
  installed.


-- Configuring done
-- Generating done
-- Build files have been written to: C:/Users/tim/Documents/c-c++/test_proj

CMakeLists.txt:

add_executable(subdir_02 main.cpp)

set(SFML_STATIC_LIBRARIES TRUE)

find_package(SFML COMPONENTS window graphics system)

target_compile_features(subdir_02 PUBLIC cxx_std_17)
target_compile_definitions(subdir_02 PRIVATE SFML_STATIC)

target_link_libraries(subdir_02 ${SFML_LIBRARIES} ${SFML_DEPENDENCIES})

Here is the main C++-file using SFML (it is in project subfolder).
.../test_proj/subdir_02/main.cpp:

#include <SFML/Graphics.hpp>

int main() {
    sf::RenderWindow app(sf::VideoMode(800, 600, 32), "Hello World - SFML");

    return 0;
}

Screenshots

project root folder screenshot

SFML folder screenshot

main.cpp-source folder


Solution

  • Dumb rule when you have a CMakeLists.txt in which dependencies are discovered with find_package(): add their install folder to CMAKE_PREFIX_PATH while calling CMake configuration.

    In you case, the CMake configuration of your project should be:

    cmake -S . -B build_release -DCMAKE_BUILD_TYPE=Release -DCMAKE_PREFIX_PATH="C:\Users\tim\Documents\c-c++\test_proj\SFML" -G "Ninja"
    

    Indeed, SFML packages provide a CMake config file SFMLConfig.cmake in a subdir. It is a possible file find_package(SFML) is trying to find. CMake cannot know where this file is, so it looks into some specific subdirs under each path listed in CMAKE_PREFIX_PATH, and eventually some standard system paths. Actually the search procedure can be very complex (https://cmake.org/cmake/help/latest/command/find_package.html#config-mode-search-procedure), but for a native build CMAKE_PREFIX_PATH is your friend.