I'm attempting to make a simple game, I have my main .cpp file which includes a header file (let's call it A) which includes all the other header files (let's call them B). In one of those B header files I have included the A file to access the programRunning
boolean which is defined in it. None of the B header files, despite including the A file which defines the variable, seem to be able to use it. I am really confused by this and would really appreciate some help. Below is the code I have used:
pong_header.h (the A header file as described above)
#ifndef PONG_HEADER_H
#define PONG_HEADER_H
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include <stdio.h>
#include "pong_graphics.h"
#include "pong_core.h"
#include "pong_entity.h"
#include "pong_event.h"
bool programRunning;
#endif
pong_event.h (one of the B header files)
#ifndef PONG_EVENT_H
#define PONG_EVENT_H
#include "pong_header.h"
void Pong_handleEvents(SDL_Event event)
{
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
programRunning = true;
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym):
case SDLK_ESCAPE:
programRunning = false;
break;
break;
default:
break;
}
Pong_handleEntityEvents(event)
}
}
The other B files access programRunning
in the same way.
The exact error Code::Blocks gives me is as follows
Pong\pong_event.h|20|error: 'programRunning' was not declared in this scope
Yes. Although this is not necessarily recommended, it can be easily accomplished with the correct set of macros and a header file. Typically, you should declare variables in C files and create extern definitions for them in header files.
To resolve this error, a first method that is helpful would be declaring the function prototype before the main() method. So, we have used the function prototype before the main method in the updated code.
The clean, reliable way to declare and define global variables is to use a header file to contain an extern declaration of the variable. The header is included by the one source file that defines the variable and by all the source files that reference the variable.
The issue is that pong_header.h
includes pong_event.h
before it declares programRunning
, so when pong_header.h
tries to include pong_event.h
, the include guards prevent it. The fix is to simply move the bool programRunning
declaration to the top of pong_event.h
.
Now, this will result in another issue - every .cpp
file that includes any of these headers will get their own copy of programRunning
, which will either cause a link error (multiple definition of programRunning
), or it will compile, but won't run the way you expect.
What you want to do is declare it as extern, i.e.
extern bool programRunning;
Then, in one of your .cpp
files (preferrably whichever has int main
), you actually declare it (i.e. without extern
):
bool programRunning;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With