Variable in header file not declared in scope

c++, header-files, scope, sdl

Solution

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;

Problem

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`

Original source