[英]Include the same header file in multiple files - 'variable' was not declared in this scope
[英]Variable in header file not declared in scope
我正在尝试制作一个简单的游戏,我有我的主要 .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
问题是, 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.