这个问题在这里已有答案:
当我在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
提前致谢!
你需要在#define _GAME_H
之间添加一个#ifndef...#endif
。在你的game.h文件中。否则,永远不会定义该值,并且#ifndef _GAME_H
不会阻止多次包含它。
编辑
虽然包含后卫是错误的,但是当我第一次阅读它时,我对这段代码并没有给予足够的重视。请阅读重复的问题,我认为game.h声明了一个类,而不仅仅是一个命名空间。