Как установить sfml на clion windows

Обновлено: 25.06.2024

This tutorial is the first one you should read if you're using SFML with the Visual Studio IDE (Visual C++ compiler). It will explain how to configure your SFML projects.

Installing SFML

First, you must download the SFML SDK from the download page.

You must download the package that matches your version of Visual C++. Indeed, a library compiled with VC++ 10 (Visual Studio 2010) won't be compatible with VC++ 12 (Visual Studio 2013) for example. If there's no SFML package compiled for your version of Visual C++, you will have to build SFML yourself.

You can then unpack the SFML archive wherever you like. Copying headers and libraries to your installation of Visual Studio is not recommended, it's better to keep libraries in their own separate location, especially if you intend to use several versions of the same library, or several compilers.

Creating and configuring a SFML project

The first thing to do is choose what kind of project to create. It is recommended to select "Empty Project". The dialog window offers a few other options to customize the project: select "Console application" or "Windows application" only if you know how to use pre-compiled headers.
For the purpose of this tutorial, you should create a main.cpp file and add it to the project, so that we have access to the C++ settings (otherwise Visual Studio doesn't know which language you're going to use for this project). We'll explain what to put inside later.

Now we need to tell the compiler where to find the SFML headers (.hpp files), and the linker where to find the SFML libraries (.lib files).

In the project's properties, add:

  • The path to the SFML headers (<sfml-install-path>/include) to C/C++ » General » Additional Include Directories
  • The path to the SFML libraries (<sfml-install-path>/lib) to Linker » General » Additional Library Directories

These paths are the same in both Debug and Release configuration, so you can set them globally for your project ("All configurations").

Screenshot of the dialog box for setting up the search paths

The next step is to link your application to the SFML libraries (.lib files) that your code will need. SFML is made of 5 modules (system, window, graphics, network and audio), and there's one library for each of them.
Libraries must be added in the project's properties, in Linker » Input » Additional Dependencies. Add all the SFML libraries that you need, for example "sfml-graphics.lib", "sfml-window.lib" and "sfml-system.lib".

Screenshot of the dialog box for setting up the project

It is important to link to the libraries that match the configuration: "sfml-xxx-d.lib" for Debug, and "sfml-xxx.lib" for Release. A bad mix may result in crashes.

The settings shown here will result in your application being linked to the dynamic version of SFML, the one that needs the DLL files. If you want to get rid of these DLLs and have SFML directly integrated into your executable, you must link to the static version. Static SFML libraries have the "-s" suffix: "sfml-xxx-s-d.lib" for Debug, and "sfml-xxx-s.lib" for Release.
In this case, you'll also need to define the SFML_STATIC macro in the preprocessor options of your project.

Screenshot of the dialog box for defining the SFML_STATIC macro

Starting from SFML 2.2, when static linking, you will have to link all of SFML's dependencies to your project as well. This means that if you are linking sfml-window-s.lib or sfml-window-s-d.lib for example, you will also have to link opengl32.lib, winmm.lib and gdi32.lib. Some of these dependency libraries might already be listed under "Inherited values", but adding them again yourself shouldn't cause any problems.

Here are the dependencies of each module, append the -d as described above if you want to link the SFML debug libraries:

You might have noticed from the table that SFML modules can also depend on one another, e.g. sfml-graphics-s.lib depends both on sfml-window-s.lib and sfml-system-s.lib. If you static link to an SFML library, make sure to link to the dependencies of the library in question, as well as the dependencies of the dependencies and so on. If anything along the dependency chain is missing, you will get linker errors.

If you are slightly confused, don't worry, it is perfectly normal for beginners to be overwhelmed by all this information regarding static linking. If something doesn't work for you the first time around, you can simply keep trying always bearing in mind what has been said above. If you still can't get static linking to work, you can check the FAQ and the forum for threads about static linking.

If you don't know the differences between dynamic (also called shared) and static libraries, and don't know which one to use, you can search for more information on the internet. There are many good articles/blogs/posts about them.

Your project is ready, let's write some code now to make sure that it works. Put the following code inside the main.cpp file:

If you chose to create a "Windows application" project, the entry point of your code has to be set to "WinMain" instead of "main". Since it's Windows specific, and your code would therefore not compile on Linux or macOS, SFML provides a way to keep a standard "main" entry point in this case: link your project to the sfml-main module ("sfml-main-d.lib" in Debug, "sfml-main.lib" in Release), the same way you linked sfml-graphics, sfml-window and sfml-system.

Now compile the project, and if you linked to the dynamic version of SFML, don't forget to copy the SFML DLLs (they are in <sfml-install-path/bin>) to the directory where your compiled executable is. Run it, and if everything works you should see this:

Screenshot of the Hello SFML application

If you are using the sfml-audio module (regardless whether statically or dynamically), you must also copy the DLL of the external library needed by it, which is OpenAL32.dll.
These files can be found in <sfml-install-path/bin> too.

Когда отправляю исполняемый файл с программой на sfml другому человеку, то у него терминал выдаёт ошибку, которая заключается в том, что не найдены динамические библиотеки. Как можно через cmake (пользуюсь clion) настроить проект так, чтобы библиотеки подключались статически? Видел решения, в которых люди заставляют программу при запуске установить через консоль отдельно sfml, если его нет, а потом уже запускать программу, но мне кажется, что это неправильное решение.

1. нужно скачать исходники sfml с их гитхаба.
2. с помощью cmake скомпилировать так, чтобы были статические библиотеки. По ходу будут возникать ошибки вида "нет библиотеки XXX" - нужно будет докачивать пакет libXXX-dev.
3. осле компиляции в файл cmake надо будет дописать:

set(SFML_DIR "путь к скомпилированному sfml/SFML-compiled")
set(CMAKE_MODULE_PATH "путь к скомпилированному sfml/SFML-compiled" $)
set(SFML_STATIC_LIBRARIES TRUE)

LoliDeveloper

Почитай туториалы на их оф сайте для своего компилятора. Там отдельные dll для статических библиотек

LoliDeveloper

If you want to get rid of these DLLs and have SFML directly integrated into your executable, you must link to the static version. Static SFML libraries have the "-s" suffix: "sfml-xxx-s-d.lib" for Debug, and "sfml-xxx-s.lib" for Release.

LoliDeveloper, где эти статические версии можно получить? Либо Clion не находит их, либо их нет в пакете вовсе. (устанавливал пакет sfml через консоль командой sudo apt-get install libsfml-dev)

LoliDeveloper

Prizm, Скачай tar архив здесь, в нём по идее должны лежать. Я сам с винды писал на sfml и там прям вперемешку с динамическими лежали статические либы

Admittedly, the title of this tutorial is a bit misleading. You will not compile SFML with CMake, because CMake is not a compiler. So. what is CMake?

CMake is an open-source meta build system. Instead of building SFML, it builds what builds SFML: Visual Studio solutions, Code::Blocks projects, Linux makefiles, XCode projects, etc. In fact it can generate the makefiles or projects for any operating system and compiler of your choice. It is similar to autoconf/automake or premake for those who are already familiar with these tools.

CMake is used by many projects including well-known ones such as Blender, CLion, KDE, Ogre, and many more. You can read more about CMake on its official website or in its Wikipedia article.

As you might expect, this tutorial is divided into two main sections: Generating the build configuration with CMake, and building SFML with your toolchain using that build configuration.

Installing dependencies

SFML depends on a few other libraries, so before starting to configure you must have their development files installed.

On Windows and macOS, all the required dependencies are provided alongside SFML so you won't have to download/install anything else. Building will work out of the box.

On Linux however, nothing is provided. SFML relies on you to install all of its dependencies on your own. Here is a list of what you need to install before building SFML:

  • freetype
  • x11
  • xrandr
  • udev
  • opengl
  • flac
  • ogg
  • vorbis
  • vorbisenc
  • vorbisfile
  • openal
  • pthread

The exact name of the packages may vary from distribution to distribution. Once those packages are installed, don't forget to install their development headers as well.

Configuring your SFML build

This step consists of creating the projects/makefiles that will finally compile SFML. Basically it consists of choosing what to build, how to build it and where to build it. There are several other options as well which allow you to create a build configuration that suits your needs. We'll see that in detail later.

The first thing to choose is where the projects/makefiles and object files (files resulting from the compilation process) will be created. You can generate them directly in the source tree (i.e. the SFML root directory), but it will then be polluted with a lot of garbage: a complete hierarchy of build files, object files, etc. The cleanest solution is to generate them in a completely separate folder so that you can keep your SFML directory clean. Using separate folders will also make it easier to have multiple different builds (static, dynamic, debug, release, . ).

Now that you've chosen the build directory, there's one more thing to do before you can run CMake. When CMake configures your project, it tests the availability of the compiler (and checks its version as well). As a consequence, the compiler executable must be available when CMake is run. This is not a problem for Linux and macOS users, since the compilers are installed in a standard path and are always globally available, but on Windows you may have to add the directory of your compiler in the PATH environment variable, so that CMake can find it automatically. This is especially important when you have several compilers installed, or multiple versions of the same compiler.

On Windows, if you want to use GCC (MinGW), you can temporarily add the MinGW\bin directory to the PATH and then run CMake from the command shell:

With Visual C++, you can either run CMake from the "Visual Studio command prompt" available from the start menu, or run the vcvars32.bat batch file of your Visual Studio installation in the console you have open. The batch file will set all the necessary environment variables in that console window for you.

Now you are ready to run CMake. In fact there are three different ways to run it:

  • cmake-gui
    This is CMake's graphical interface which allows you to configure everything with buttons and text fields. It's very convenient to see and edit the build options and is probably the easiest solution for beginners and people who don't want to deal with the command line.
  • cmake
    This is the direct call to CMake. If you use this, you must specify all the option names and their values as command line parameters. To print out a list of all options, run cmake -L.

In this tutorial we will be using cmake-gui, as this is what most beginners are likely to use. We assume that people who use the command line variants can refer to the CMake documentation for their usage. With the exception of the screenshots and the instructions to click buttons, everything that is explained below will apply to the command line variants as well (the options are the same).

Here is what the CMake GUI looks like:

Screenshot of the cmake-gui tool

The first steps that need to be done are as follows (perform them in order):

  1. Tell CMake where the source code of SFML is (this must be the root folder of the SFML folder hierarchy, basically where the top level CMakeLists.txt file is).
  2. Choose where you want the projects/makefiles to be generated (if the directory doesn't exist, CMake will create it).
  3. Click the "Configure" button.

If this is the first time CMake is run in this directory (or if you cleared the cache), the CMake GUI will prompt you to select a generator. In other words, this is where you select your compiler/IDE.

Screenshot of the generator selection dialog box

For example, if you are using Visual Studio 2010, you should select "Visual Studio 10 2010" from the drop-down list. To generate makefiles usable with NMake on the Visual Studio command line, select "NMake Makefiles". To create makefiles usable with MinGW (GCC), select "MinGW Makefiles". It is generally easier to build SFML using makefiles rather than IDE projects: you can build the entire library with a single command, or even batch together multiple builds in a single script. Since you only plan to build SFML and not edit its source files, IDE projects aren't as useful.

The installation process (described further down) may not work with the "Xcode" generator. It is therefore highly recommended to use the Makefile generator when building on macOS.

Always keep the "Use default native compilers" option enabled. The other three fields can be left alone.

After selecting the generator, CMake will run a series of tests to gather information about your toolchain environment: compiler path, standard headers, SFML dependencies, etc. If the tests succeed, it should finish with the "Configuring done" message. If something goes wrong, read the error(s) printed to the output log carefully. It might be the case that your compiler is not accessible (see above) or configured properly, or that one of SFML's external dependencies is missing.

Screenshot of the cmake-gui window after configure

After configuring is done, the build options appear in the center of the window. CMake itself has many options, but most of them are already set to the right value by default. Some of them are cache variables and better left unchanged, they simply provide feedback about what CMake automatically found.
Here are the few options that you may want to have a look at when configuring your SFML build:

This option selects the build configuration type. Valid values are "Debug" and "Release" (there are other types such as "RelWithDebInfo" or "MinSizeRel", but they are meant for more advanced builds).

Note that if you generate a workspace for an IDE that supports multiple configurations, such as Visual Studio, this option is ignored since the workspace can contain multiple configurations simultaneously.

This is the install path. By default, it is set to the installation path that is most typical on the operating system ("/usr/local" for Linux and macOS, "C:\Program Files" for Windows, etc.). When building frameworks on macOS, you may want to change the value to "/Library/Frameworks".

Installing SFML after building it is not mandatory since you can use the binaries directly from where they were built. It may be a better solution, however, to install them properly so you can remove all the temporary files produced during the build process.

This is the path where SFML's dependencies like Freetype and OpenAL are installed. By default it is the same as CMAKE_INSTALL_PREFIX , except on macOS where it defaults to "/Library/Frameworks", because dependencies on macOS are provided as frameworks.

As stated above for CMAKE_INSTALL_PREFIX , it is not mandatory to install SFML after building it but it is definitely cleaner to do so.

This is the path where SFML examples, documentation, license and readme files are installed. On Windows it defaults to CMAKE_INSTALL_PREFIX and to CMAKE_INSTALL_PREFIX/share/SFML on FreeBSD, Linux. On macOS, it defaults to "/usr/local/share/SFML".

After everything is configured, click the "Configure" button once again. There should no longer be any options highlighted in red, and the "Generate" button should be enabled. Click it to finally generate the chosen makefiles/projects.

Screenshot of the cmake-gui window after generate

CMake creates a variable cache for every project. Therefore, if you decide to reconfigure something at a later time, you'll find that your settings have been saved from the previous configuration. Make the necessary changes, reconfigure and generate the updated makefiles/projects.

Building SFML

Let's begin this section with some good news: you won't have to go through the configuration step any more, even if you update your working copy of SFML. CMake is smart: It adds a custom step to the generated makefiles/projects, that automatically regenerates the build files whenever something changes.

You're now ready to build SFML. Of course, how to do it depends on what makefiles/projects you've generated. If you created a project/solution/workspace, open it with your IDE and build SFML like you would any other project. We won't go into the details here, there are simply too many different IDEs and we have to assume that you know how to use yours well enough to perform this simple task on your own.

If you generated a makefile, open a command shell and execute the make command corresponding to your environment. For example, run "nmake" if you generated an NMake (Visual Studio) makefile, "mingw32-make" if you generated a MinGW (GCC) makefile, or simply "make" if you generated a Linux makefile.
Note: On Windows, the make program (nmake or mingw32-make) may not be accessible. If this is the case, don't forget to add its location to your PATH environment variable. See the explanations at the beginning of the "Configuring your SFML build" section for more details.

By default, building the project will build everything (all the SFML libraries, as well as all the examples if you enabled the SFML_BUILD_EXAMPLES option). If you just want to build a specific SFML library or example, you can select a different target. You can also choose to clean or install the built files, with the corresponding targets.
Here are all the targets that are available, depending on the configure options that you chose:

If you use an IDE, a target is simply a project. To build a target, select the corresponding project and compile it (even "clean" and "install" must be built to be executed -- don't be confused by the fact that no source code is actually compiled).
If you use a makefile, pass the name of the target to the make command to build the target. Examples: " nmake doc ", " mingw32-make install ", " make sfml-network ".

Как подключить библиотеку sfml к g++?
как подключить библиотеку sfml на g++ компилятор?


Не получается подключить библиотеку SFML
Не получается подключить SFML библиотеку в Visual Studio. Делал как тут Но при.

Не могу подключить SFML к Code::Blocks 16.01
Система Windows 7 64 битная, компилятор mingw32 версия 4.9.2 шёл вместе с IDE. Компилировал файл с.

Скачайте SFML.cmake и подключайте без проблем.
Либо руками прописывайте необходимые параметры. А вы не могли бы несколько подробнее объяснить? Сейчас я скачиваю SFML для GCC 6.1.0 MinGW (SEH) - 64-bit, скачиваю сам компилятор, устанавливаю этот компилятор по умолчанию в Clion, а что дальше делать - не совсем понимаю если честно. а что дальше делать - не совсем понимаю если честно.

Вы не правильный вопрос задаете.
CLion использует cmake, а значит
нужно учиться работать с cmake.


Если "в лоб", то необходимо указать компилятору
путь до папки include библиотеки SFML,
а линкеру указать путь до библиотек SFML.

Да, я по этому мануалу и пытаюсь настроить. Проблема в том, что , на сколько я понимаю - при настройке как в примере предполагается, что у меня уже где-то в нужном месте лежит сама библиотека. Я делаю все как в примере, но так и не могу разобраться как указать компилятору
путь до папки include библиотеки SFML,
а линкеру указать путь до библиотек SFML. Добавлено через 30 минут
Попробовал сделать все как в ЭТОМ видео - ошибка все равно никуда не исчезла.
Код ошибки:
CMake Error at cmake_modules/FindSFML.cmake:355 (message):
Could NOT find SFML (missing: SFML_NETWORK_LIBRARY SFML_AUDIO_LIBRARY
SFML_GRAPHICS_LIBRARY SFML_WINDOW_LIBRARY SFML_SYSTEM_LIBRARY)
Call Stack (most recent call first):
CMakeLists.txt:32 (find_package)

SFML в C::B пытается что-то найти в D:\sfml-release\ которого нет
Добрый день, вторые сутки пытаюсь подключить SFML библиотеку к C::B. При подключении по мануалу с.


D:\C++ Projekts\SFML\main.cpp [Error] SFML\Graphics.hpp: No such file or directory
Пытаюсь начать кодить на библиотеке SFML но при компиляции пучтого проэкта выдает .


Создание релиза exe файла SFML C++ на VS 2017 (не удается открыть входной файл "sfml-graphics-s.lib")
не могу собрать решение релиз версии, не пойму что я делаю не так постоянно выдает ошибку 1&gt;LINK.

CLion, SFML
Недавно скачал и поставил мультимедийную библиотеку SFML, решил опробовать, но выдаёт ошибки. Не.

Читайте также: