我收到有关“已经在game.obj中定义”的错误。我该怎么办?

时间:2019-05-01 03:25:51

标签: c++ compiler-errors sdl sdl-2

当我在Visual Studio 2019中使用SDL2时,遇到了一些错误:

   1>Source.obj : error LNK2005: "struct SDL_Window * game::gWindow" (?gWindow@game@@3PAUSDL_Window@@A) already defined in game.obj
   1>Source.obj : error LNK2005: "struct SDL_Surface * game::gScreenSurface" (?gScreenSurface@game@@3PAUSDL_Surface@@A) already defined in game.obj
   1>Source.obj : error LNK2005: "struct SDL_Surface * game::gImage" (?gImage@game@@3PAUSDL_Surface@@A) already defined in game.obj

我抬起头来如何解决它都无济于事。我尝试使用externs,更改了我的game.h文件,但没有任何效果。就像一些背景信息一样,我正在尝试使用SDL2做一个游戏引擎类型的东西,以在将来进行游戏开发时为我提供帮助。我想保留尽可能多的代码,而不要删除太多代码。

这是我的代码: Source.cpp

    #include <SDL.h>
    #include "game.h"
    #include <stdio.h>

    int main(int argc, char* args[]) {
        if (!game::init()) { // SDL failed it initialize
            printf("error");
        }
        else { // SDL was able to initialize
            if (!game::loadMedia()) { // Could not load media
                printf("error");
            }
            else { // Could load media
                SDL_BlitSurface(game::gImage, NULL, game::gScreenSurface, NULL);
            }
        }
        return 0;
    }

game.cpp

#include <SDL.h>
#include "game.h"
#include <stdio.h>

namespace game { //functions
    bool init() {
        bool success = true;
        if (SDL_Init(SDL_INIT_VIDEO) < 0) {
            printf("SDL failed to initialize.\n");
            success = false;
        }
        else {
            gWindow = SDL_CreateWindow(
                "SDL Window (;", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN
            );
            if (gWindow == NULL)
            {
                printf("Window could not be created! SDL_Error: %s\n", SDL_GetError());
                success = false;
            }
            else
            {
                //Get window surface
                gScreenSurface = SDL_GetWindowSurface(gWindow);
            }
        }
        return success;
    }
    bool loadMedia() {
        // Loading success flag
        bool success = true;
        // File name of image
        const char* fileName = "mario.bmp";
        // Load splash image
        gImage = SDL_LoadBMP(fileName);
        if (gImage == NULL)
        {
            printf("Unable to load image '%s'! SDL Error: %s\n", fileName, SDL_GetError());
            success = false;
        }

        return success;
    }
}

和game.h

#ifndef _GAME_H

namespace game {
    SDL_Window* gWindow;
    SDL_Surface* gScreenSurface;
    SDL_Surface* gImage;

    const int SCREEN_WIDTH = 640;
    const int SCREEN_HEIGHT = 480;

    bool init();
    bool loadMedia();
}
#endif

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要在#define _GAME_H之间添加#ifndef...#endif。在您的game.h文件中。否则,永远不会定义该值,并且#ifndef _GAME_H不会阻止多次包含它。

编辑

尽管包含保护是错误的,但是当我第一次阅读该代码时,我并没有对此代码给予足够的重视。请阅读重复的问题,我认为game.h声明了一个类,而不仅仅是一个名称空间。