之前写过一篇Clion配置C++/SFML开发环境(Win10),由于Clion是收费的IDE,免费的IDE目前靠谱的选择只有Visual Studio,因此再写一篇基于Visual Studio 2022的教程。由于SFML未提供编译好的基于Visual Studio 2022的版本,因此这里需要自己编译。

环境

  1. 操作系统: windows 10 版本 1909 (内部版本 18363.1646)
  2. IDE: Microsoft Visual Studio Community 2022 (64 位) 版本 17.2.5
  3. CMake: cmake-gui 3.24.0-rc2
  4. SFML: 2.6.x (Github源码编译)

步骤

  1. Github下载2.6.x分支SFML源码
  2. 打开CMake-gui,如图所示,选择下载好SFML源代码目录,任意设置一个build目录,然后点击Configure
    Cmake1
  3. 选择Visual Studio 2022作为generator,点击Finish
    Cmake2
  4. 此时Configure开始执行,执行完(Configuring done)成会出现红色的参数需要设置,如下图所示,一般都不用改,我这里把CMAKE_INSTALL_PREFIX改成另一个指定的目录,然后再次点击Configure
    Cmake3
  5. 第二次Configure完成之后,不再有红色参数,点击旁边的Generate,执行完成后,点击Open Project
    Cmake4
  6. 此时会打开Visual Studio 2022,执行INSTALL -> 生成,即可把SFML安装在指定的目录。
    Install
  7. 通过Visual Studio 2022再新建一个CMake项目,CMakeLists.txt内容如下

        cmake_minimum_required (VERSION 3.8)
        project("SFMLTest")
    
        # 设置SFML目录
        set(SFML_DIR "D:\\Program Files\\SFML\\lib\\cmake\\SFML")
    
        find_package(SFML REQUIRED COMPONENTS audio network graphics window system)
    
        if (NOT SFML_FOUND)
            message(FATAL_ERROR "SFML NOT FOUND!")
        else()
            message("SFML FOUND!")
        endif()
    
        include_directories(${SFML_INCLUDE_DIR})
        add_executable (SFMLTest "SFMLTest.cpp" "SFMLTest.h")
        if (CMAKE_VERSION VERSION_GREATER 3.12)
        set_property(TARGET SFMLTest PROPERTY CXX_STANDARD 20)
        endif()
    
        target_link_libraries("SFMLTest" sfml-main sfml-audio sfml-network sfml-graphics sfml-window sfml-system)
    
        # 把DLL复制到执行目录
        set(
            DLL_FILES
            "D:\\Program Files\\SFML\\bin\\sfml-graphics-2.dll"
            "D:\\Program Files\\SFML\\bin\\sfml-window-2.dll"
            "D:\\Program Files\\SFML\\bin\\sfml-system-2.dll"
        )
        foreach(DLL_FILE ${DLL_FILES})
            message("Found DLL to Copy: ${DLL_FILE}")
            add_custom_command(
                TARGET SFMLTest PRE_BUILD
                COMMAND ${CMAKE_COMMAND} -E copy ${DLL_FILE} ${CMAKE_BINARY_DIR}.
            )
        endforeach()
  8. 测试以下代码,执行成功将绘制一个绿色的圆

        #include <SFML/Graphics.hpp>
    
        using namespace std;
    
        int main()
        {
            sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
            sf::CircleShape shape(100.f);
            shape.setFillColor(sf::Color::Green);
    
            while (window.isOpen())
            {
                sf::Event event;
                while (window.pollEvent(event))
                {
                    if (event.type == sf::Event::Closed)
                        window.close();
                }
    
                window.clear();
                window.draw(shape);
                window.display();
            }
    
            return 0;
        }
  9. 运行成功
    SFML

Harpsichord1207
538 声望44 粉丝

前路漫漫