C++ 和 SDL 2 - 创建 constants-only header:对 Constants::window 的未定义引用

C++ and SDL 2 - Creating a constants-only header: undefined reference to Constants::window

所以我用 C++ 和 SDL 2 开始了一个空闲时间的游戏项目,运行 遇到了一个令人费解的问题。

我有一个 header 文件,我打算在其中存储全局使用的数据。

class Constants {
public:
    static SDL_Window* window;

    const static int w = 640;
    const static int h = 480;
};

现在,当我在别处引用 window 时,会出现 "undefined reference" 错误。我试过在main函数前加一个null定义,还是不行。

所以问题就来了:

SDLManager::SDLManager() {

    // ......

    // THIS BREAKS
    Constants::window = SDL_CreateWindow("Caption", 
        SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 
        Constants::w, Constants::h, SDL_WINDOW_SHOWN);
}

出了什么问题,我该怎么办?我以前用 SDL 1 成功编码过。

至少,您需要在 header.

中转发声明 SDL_Window class

此外,如果以上是 linker 错误,您将需要让编译器知道 link 使用哪个库以及在哪里找到它。

我在自己的游戏开发过程中也遇到过类似的问题(虽然我用的是Allegro)

您需要做的是定义有问题的 variable/class。你只是宣布了它。您现在需要定义它。

// constants.h
class Constants {
    public:
    static SDL_Window* window;

    const static int w = 640;
    const static int h = 480;
};

// constants.cpp
#include "constants.h"

Constants::SDL_Window *window;

如果我的语法有一点偏差,我很乐意得到纠正。