Abdul Ghani
Abdul Ghani

Reputation: 83

Values in a header being set to NULL when included after being defined

I'm writing a simple game in C++ using SDL. I have written a more complicated game before, but it was in one source file consisting of 4000+ lines of code.

My problem is that variables seem to be being reset at the end of the .cpp file they are defined in.

In Declarations.cpp (Amongst other things)

bool CheckFiles()
{
    SDL_Surface *Background = LoadImage("Resources/Images/Background.png");
    SDL_Surface *Character1 = LoadImage("Resources/Images/Character.png");
    SDL_Surface *MenuBackground = LoadImage("Resources/Images/MenuBackground.png");
    TTF_Font *EightBitLimit = TTF_OpenFont("Resources/Fonts/EightBitLimit.ttf",16);
    TTF_Font *KarmaFuture = TTF_OpenFont("Resources/Fonts/KarmaFuture.ttf",16);
    TTF_Font *EightBitLimitSmall = TTF_OpenFont("Resources/Fonts/EightBitLimit.ttf",9);
    SDL_Surface *Message1 = NULL;
    SDL_Surface *Message2 = NULL;

    if (Background == NULL) return false;
    if (Character1 == NULL) return false;
    if (MenuBackground == NULL) return false;
    if (EightBitLimit == NULL) return false;
    if (KarmaFuture == NULL) return false;
    if (EightBitLimitSmall == NULL) return false; //Breakpoint here, everything has loaded fine
    return true;
}

In Menu.cpp

#include"Declarations.h"
#include"Menu.h"

void Menu()
{
    while (Quit == false && State == MENU)
    {
        CheckFiles();
        ApplySurface(0,0,MenuBackground,Screen); //Gives an access violation as all surfaces and fonts have became NULL
        Message1 = TTF_RenderText_Solid(KarmaFuture,"Tripping Octo Dangerzone",White);

My header files are properly guarded. Variables and functions are declared like so:

extern TTF_Font *KarmaFuture;
extern bool CheckFiles();

My main.cpp file:

#include"Declarations.h"
#include"Menu.h"
#include"Game.h"

int main (int argc, char* argv [])
{
    if (Init() == false) return -1;
    if (CheckFiles() == false) return -1; //Everything is initialized and loaded properly
    while (Quit == false)
    {
        switch(State)
            {
    case MENU:
        Menu();
        break;
    case GAME:
        Game();
        break;
    }
}
return 0;

}

This is my first time working with header files, so sorry if my mistake is glaringly obvious. Thank you for any help in advance.

Upvotes: 0

Views: 196

Answers (1)

unwind
unwind

Reputation: 399833

You're not checking the same variable.

The

SDL_Surface *MenuBackground = LoadImage("Resources/Images/MenuBackground.png");

line in CheckFiles() declares a local variable called MenuBackground. This variable has nothing to do with any other variable of the same name at any other location in your program (except the scope that line is in, and any child-scopes).

Upvotes: 2

Related Questions