我正在尝试制作一个简单的游戏,我有我的主 .cpp 文件,其中包含一个头文件(我们称之为 A),其中包含所有其他头文件(我们称之为 B)。在其中一个 B 头文件中,我包含了 A 文件以访问其中定义的 programRunning
bool 值。尽管包含定义变量的 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|错误:“programRunning”未在此范围内声明
最佳答案
问题是 pong_header.h
包括 pong_event.h
在 它声明 programRunning
之前,所以当 pong_header.h
尝试包含 pong_event.h
,包含守卫会阻止它。解决方法是简单地将 bool programRunning
声明移动到 pong_event.h
的顶部。
现在,这将导致另一个问题 - 每个包含任何这些 header 的 .cpp
文件都将获得它们自己的 programRunning
拷贝,这将导致链接错误(programRunning
的多个定义),或者它将编译,但不会按您期望的方式运行。
您要做的是将其声明为extern,即
extern bool programRunning;
然后,在一个你的.cpp
文件中(最好有int main
),你实际声明它(即没有 extern
):
bool programRunning;
关于c++ - 头文件中的变量未在范围内声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18233566/