C++多个文件并包括标题
C++ Multiple Files & Including Headers
几个月来我一直想自己弄清楚这个问题,这一点也不夸张。
我觉得使用我不喜欢的方法很脏,因为当事情变得复杂时,事情往往会破裂并超出范围,而我在任何地方都找不到答案。
我有一个项目结构如下:
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.cpp
、gamestate.cpp
、init.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.cpp
对logic.cpp
中的函数使用的原型,除非我隐式地将logic.h
包含在gamestate.h
中,即使logic.h
在gamestate.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"可能是个坏主意。
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 为什么 cmake 许可证<>样式不包括?
- 包括C++标题,"..."与<...>风格,ISO / IEC官方意见?
- 包括没有标题的文件
- 由于QT MOC,将标题包括在标题文件中
- VC 链接器错误使用Dllimport/DLLEXPORT宏将标题包括在多个项目中
- C 在两个标题文件中包括一个类
- 包括通过CMAKE工具链正确版本的STL标题
- Cmake仅包括仅来自标头目标的标题目标
- 包括带有性细胞群的标题
- 包括来自预构建库Android.mk的标题文件
- 如何将标题文件包括在C DLL文件中
- 包括(STL)标题中的标题文件
- 将标题包括在makefile中
- C++标题和CPP包括
- C++多个文件并包括标题
- Qt 5.0,包括个人标题问题
- 包括子文件夹中的标题