C ++ Multiple Files&包括标题

时间:2013-06-01 08:57:27

标签: c++ header-files

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

我觉得使用我不喜欢的方法很脏,因为当它们变得复杂时,事情往往会破坏并超出范围,我无法在任何地方找到答案。

我的项目结构如下:

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.cppinit.cpp,所有人都包含gamestate.h

在每个文件夹中只有一个头文件,最近从每个.cpp的1个头文件重新组织。

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

为什么如果我的标题文件包含在#include <iostream>之后和main.cpp中的SDL库之后。

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

// C++ Libraries
#include <iostream>

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

但后来我一遍又一遍地包括同样的事情,当然这是不好的做法。

不仅如此,gamestate.h包含gamestate.cpp用于logic.cpp中的函数的原型,除非我在{{1}中隐式包含logic.h,否则会获得范围错误即使在gamestate.h之前logic.h中包含main.cpp

我认为gamestate.h旨在将头文件的内容拖放到作用域及其原型的函数中,以便编译器知道会发生什么。

为什么我收到关于作用域和功能不存在的所有错误?

我应该在那里制作#includeglobal.h所有SDL和#include内容吗?

为什么我无法在<iostream>中的其他文件中访问logic.h中的原型函数?

1 个答案:

答案 0 :(得分:1)

这有点像“你能做多种方式,没有一种是对或错”的问题。

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

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

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

相关问题