创建简单项目时,CMake 无法在 Windows 中找到 SFML 目录

CMake is unable to find SFML directories in Windows when creating a simple project

我最近为 Windows 下载了 CMake,因为我想为 SFML 开发一个跨平台插件,并决定按照 here. As per the guide, I created a folder in my Documents directory called sfml_test_cmake (Windows 10) with a CMakeLists.txt, main.cpp (which has the SFML code), and a folder cmake_modules which would hold a file FindSFML.cmake 的指南来测试如何做到这一点. CMakeLists.txt 如下所示:

cmake_minimum_required(VERSION 3.9)
project(SFML-CmakeTest)

set(EXECUTABLE_NAME "sfml_test_cmake")

add_executable(${EXECUTABLE_NAME} main.cpp)

set(CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake_modules" ${CMAKE_MODULE_PATH})
find_package(SFML 2.4 REQUIRED system window graphics network audio)
target_link_libraries(${EXECUTABLE_NAME} ${SFML_LIBRARIES})

install(TARGETS ${EXECUTABLE_NAME} DESTINATION bin)

main.cpp,这是一个简单的测试程序,如下所示:

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow testWindow{ sf::VideoMode{ 640, 480 }, "Test Window", sf::Style::Default };

    while (testWindow.isOpen())
    {
        sf::Event winEvent;
        while (testWindow.pollEvent(winEvent))
        {
            if (winEvent.type == sf::Event::Closed)
            {
                testWindow.close();
            }
        }
        testWindow.clear();
        testWindow.display();
    }
}

至于安装 SFML 的位置,它安装在我的文档目录和我的 C:\ 驱动器中。为了最终构建代码,我打开了 cmd.exe,在我的文件夹中为构建创建了一个新目录,然后 运行 cmake ..。我得到的错误是:

CMake Error at cmake_modules/FindSFML.cmake:357 (message):
  Could NOT find SFML (missing: SFML_SYSTEM_LIBRARY SFML_WINDOW_LIBRARY
  SFML_GRAPHICS_LIBRARY SFML_NETWORK_LIBRARY SFML_AUDIO_LIBRARY)

在查看 FindSFML.cmake 后,我发现了这个:

# define the list of search paths for headers and libraries
set(FIND_SFML_PATHS
    ${SFML_ROOT}
    $ENV{SFML_ROOT}
    ~/Library/Frameworks
    /Library/Frameworks
    /usr/local
    /usr
    /sw
    /opt/local
    /opt/csw
    /opt)

这告诉我 Cmake 只在 SFML 所在的目录中搜索,如果我在 Linux,解释了为什么找不到目录。为了解决这个问题,我将函数更改为以下内容:

# define the list of search paths for headers and libraries
set(FIND_SFML_PATHS
    ${SFML_ROOT}
    $ENV{SFML_ROOT}
    ~/Library/Frameworks
    /Library/Frameworks
    /usr/local
    /usr
    /sw
    /opt/local
    /opt/csw
    /opt
    C:/)

但是,这次重建还是报同样的错误,搞得我一头雾水。我做错了什么?

请勿修改原文FindSFML.cmake。相反,定义一个包含路径的变量 CMAKE_PREFIX_PATH,您的计算机上应该安装 SFML。添加 "C:\" 到搜索路径列表是行不通的,cmake 不会递归搜索指定路径中的所有目录。