C++多个文件并包括标题

C++ Multiple Files & Including Headers

本文关键字:包括 标题 文件 C++      更新时间:2023-10-16

几个月来我一直想自己弄清楚这个问题,这一点也不夸张。

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

我有一个项目结构如下:

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的一个头文件重组。

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

如果我的头文件被包含在#include <iostream>main.cpp中的SDL库之后,为什么会这样?

我解决了这个错误插入到所有的头文件:

// C++ Libraries
#include <iostream>
// Graphical Libraries
#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>

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

不仅如此,而且gamestate.h包含gamestate.cpplogic.cpp中的函数使用的原型,除非我隐式地将logic.h包含在gamestate.h中,即使logic.hgamestate.h之前包含在main.cpp中。

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

为什么我得到所有这些关于作用域和函数不存在的错误?

我应该做一个global.h#include所有的SDL和<iostream>的东西吗?

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

这是一种"你可以做很多事情,没有一个是完全正确或错误"的问题。

但是从技术上讲,源文件需要包含它所依赖的所有头文件。所以如果"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"可能是个坏主意。