简体   繁体   中英

c++ header file redefenition error

*note: I am new to c++, so sorry if I make an obvious mistake.

I am getting an error on all of my variables. I am trying to use headers and forward declarations. Here is a snippet of my code:

//BotRenderer.h
#ifndef BOTRENDERER_H_
#define BOTRENDERER_H_
#include <SDL2/SDL.h>
SDL_Texture *botTextures[217];
int currentBotFrame;

//BotRenderer.cpp
#include "BotRenderer.h"
SDL_Texture *botTextures[217];
int currentBotFrame = 0;

All of the lines with variables give the error, '[variable name here] previously declared here'. What can I do to fix this?

The problem is that include guards only protect against multiple inclusion in the same translation unit (source file).

If you define a variable in a header file and include it in more than one source file then the variable will be defined in both source files (translation units), and when you then link the generated object files together the linker will notice that the variable is defined in both object files and give you an error.

What you should do is declare the variables in the header file, the easiest to do it is to add the extern keyword before the declaration, like

extern SDL_Texture *botTextures[217];
extern int currentBotFrame;

Regarding your compiler error, you get it just because you define the variables in both the header file and in the source file. The solution you your problem is the same, declare in header file and define in source file.

You should read about the One Definition Rule (aka ODR) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM