【问题标题】:Variable in header file not declared in scope头文件中的变量未在范围内声明
【发布时间】:2013-08-14 13:48:12
【问题描述】:

我正在尝试制作一个简单的游戏,我有一个主 .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

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)
    }
}

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

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

【问题讨论】:

  • 您发布的内容应该可以使用。我怀疑您所描述的与实际发生的情况略有不同?
  • 让它extern bool programRunning;并在源中也有它。 (布尔运行)。如果它是 dll,请不要忘记用 import/export 来装饰它

标签: c++ scope sdl header-files


【解决方案1】:

问题在于pong_header.h 包含pong_event.h 之前 它声明了programRunning,所以当pong_header.h 尝试包含pong_event.h 时,包含守卫会阻止它。解决方法是简单地将bool programRunning 声明移动到pong_event.h 的顶部。

现在,这将导致另一个问题 - 每个包含这些标头的 .cpp 文件都将获得它们自己的 programRunning 副本,这将导致链接错误(programRunning 的多个定义),或者它编译,但不会按照你期望的方式运行。

您要做的就是将其声明为extern,即

extern bool programRunning;

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

bool programRunning;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2016-09-18
    • 2017-02-12
    • 1970-01-01
    • 2019-03-06
    • 1970-01-01
    相关资源
    最近更新 更多