编译器找不到 SDL2 类。如何正确地包含和 link 它们?

Compiler can't find SDL2 classes. How to properly include and link them?

我刚开始接触 C++。我下载了这个 simple helicopter game 并尝试编译它,但我不知道如何正确包含和 link SDL2 依赖项。

我的第一个方法是尝试用 gcc 编译它。我得到了以下命令:

gcc main.cpp ^
-I C:\code\SDL2\SDL2-2.0.22\include ^
-I C:\code\SDL2\SDL2_image-2.0.5\include ^
-I C:\code\SDL2\SDL2_mixer-2.0.4\include ^
-I C:\code\SDL2\SDL2_ttf-2.0.18\include ^
-L C:\code\SDL2\SDL2-2.0.22\lib\x64 ^
-L C:\code\SDL2\SDL2_image-2.0.5\lib\x64 ^
-L C:\code\SDL2\SDL2_mixer-2.0.4\lib\x64 ^
-L C:\code\SDL2\SDL2_ttf-2.0.18\lib\x64

但是编译器抱怨无法从 SDL2 库中找到 类 和函数。例如,它给出的许多错误中的第一个是

In file included from heli.h:4:0,
                 from main.cpp:7:
loader.h: In function 'SDL_Surface* load_image(std::__cxx11::string, int)':
loader.h:27:57: error: 'SDL_DisplayFormat' was not declared in this scope
         optimizedImage = SDL_DisplayFormat( loadedImage );

然后我尝试将代码库变成一个Visual Studio项目并按照this tutorial配置它,基本上有以下配置:

但后来我得到了完全相同的缺失依赖项,如“未找到标识符 'foo'”或“'bar':未声明的标识符”。关于包含和 linking C++ 依赖项,我错过了什么?

  1. 游戏的源代码引用的是 SDL 而不是 SDL2。自版本 1 以来,函数名称或实现有可能发生了变化。实际上,如果您下载 SDL 和 SDL2 并在这两个版本中查找 SDL_video.h 文件,您会看到 SDL_DisplayFormat 在SDL_video 版本 1 的头文件,但版本 2 中没有。

  2. 至于包含过程,最好的方法是在您使用的 IDE 中设置它。例如,在 Visual Studio 中,您可以通过在“解决方案属性 -> 常规属性 -> C/C++ -> 所有选项 -> 附加包含目录”中添加目录来实现。否则,我相信您需要知道正确的包含顺序,否则 gcc 会抱怨。 检查此讨论: Why does the order in which libraries are linked sometimes cause errors in GCC?