头文件中的变量未在范围中声明

ftm*_*ftm 5 c++ scope sdl header-files

好吧,我知道一些类似的问题可能已经放在这里,但我在互联网上的任何地方都找不到任何关于这个的东西,所以我只能假设它是因为我对C++没有那么好,我做错了没有实现.

在我正在制作的游戏中,我有我的主.cpp文件,其中包含一个头文件(我们称之为A),其中包含所有其他头文件(让我们称之为B).在其中一个B头文件中,我包含了一个A文件来访问programRunning其中定义的布尔值.尽管包含定义变量的A文件,B头文件中的任何一个似乎都无法使用它.我真的很困惑,非常感谢一些帮助.以下是我使用过的代码:

pong_header.h(如上所述的A头文件)

#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
Run Code Online (Sandbox Code Playgroud)

pong_event.h(B头文件之一)

#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)
    }
}
Run Code Online (Sandbox Code Playgroud)

其他B文件programRunning以相同的方式访问.

Code :: Blocks的确切错误给出如下 Pong\pong_event.h|20|error: 'programRunning' was not declared in this scope

Dre*_*wen 7

问题是声明之前pong_header.h包含,因此当试图包含时,包含保护会阻止它.解决方法是简单地将声明移到顶部.pong_event.h programRunningpong_event.hpong_event.hbool programRunningpong_event.h

现在,这将导致另一个问题-每一个.cpp包含这些头都将获得自己的副本文件programRunning,这将导致任何一个环节出错(多重定义programRunning),否则编译,但不能运行你的方式期望.

你想要做的是将它声明为extern,即

extern bool programRunning;
Run Code Online (Sandbox Code Playgroud)

然后,在你的一个.cpp文件中(最好是哪个int main),你实际上是声明它(即没有 extern):

bool programRunning;
Run Code Online (Sandbox Code Playgroud)