2

几个月来,我一直试图自己解决这个问题,这并不夸张。

使用我不使用的方法时,我感到很脏,因为当事情变得复杂时,事情往往会破裂并超出范围,而我在任何地方都找不到答案。

我有一个项目结构如下:

Project-Directory/
main.cpp
makefile
SDLMain.h // SDL libraries required to be in the project directory.
SDLMain.m // SDL libraries required to be in the project directory.

--- gamestate/
------ clean.cpp
------ gamestate.cpp
------ gamestate.h
------ init.cpp

--- graphics/
------ graphics.h
------ // more .cpp files

--- logic/
------- logic.h
------- // more .cpp files

--- character
------- character.h
------- // more .cpp files

main.cpp我有:

// C++ Libraries
#include <iostream>

// Graphical Libraries
//#include <SDL/SDL.h>
//#include <SDL/SDL_opengl.h>

// Custom Libraries
#include "character/character.h"
#include "logic/logic.h"
#include "graphics/graphics.h"
#include "gamestate/gamestate.h"

字符和图形等中的所有 .cpp 文件都包含它们各自与文件夹同名的头文件。即clean.cppgamestate.cpp所有init.cpp包括gamestate.h

每个文件夹中只有一个头文件,最近从每个 .cpp 1 个头文件重组而来。

基本上,在这个新的、更结构化的系统上,当我尝试编译我的项目时,我会遇到范围错误。

如果我的头文件被包含在之后#include <iostream>并且 SDL 库包含在main.cpp.

我通过将其插入所有头文件来解决了该错误:

// C++ Libraries
#include <iostream>

// Graphical Libraries
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>

但后来我一遍又一遍地包含同样的东西,这肯定是不好的做法。

不仅如此,还gamestate.h包含一个函数使用的原型,gamestate.cpp在该函数中logic.cpp会出现范围错误,除非我隐式包含logic.h在其中,gamestate.h即使logic.h它包含在main.cppbefore中gamestate.h

我认为#include这是为了将头文件的内容拖到范围和它的原型中,以便编译器知道会发生什么。

为什么我会收到所有这些关于范围和功能不存在的错误?

我应该在那里制作一个global.h#include所有的 SDL 和<iostream>东西吗?

为什么我不能logic.h从后面包含的另一个文件访问原型化的函数main.cpp

4

1 回答 1

2

这是一种“你可以通过多种方式做到这一点,没有一种是完全正确或错误的”问题。

但从技术上讲,源文件需要包含它所依赖的所有头文件。因此,如果“gamestate.cpp”需要“logic.cpp”中的某些内容,那么“gamestate.cpp”需要包含“logic.h”。如果使用“gamestate.h”的每个地方也需要“logic.h”,那么“gamestate.h”可能应该包含“logic.h”,但我曾在规则如下的系统上工作过:如果你要使用“ gamestate.h”,您必须首先包含“logic.h”。请注意,“gamestate.cpp”不是在“main.cpp”中编译的(除非你犯下了将“gamestate.cpp”包含在“main.cpp”中的令人发指的罪行——但请不要这样做)。

我喜欢你可以直接使用头文件,而不必记住必须在它之前添加的头文件列表。

使用“global.h”可能是个坏主意。

于 2013-06-01T09:05:56.917 回答