C ++类的头文件组织 [英] C++ class header files organization
问题描述
对于那些必须处理大量相互依赖的类的人来说,C ++编码和文件组织的指导是什么,这些指南遍布多个源文件和头文件?
What are the C++ coding and file organization guidelines you suggest for people who have to deal with lots of interdependent classes spread over several source and header files?
这个情况在我的项目和解决类定义相关的错误跨越几个头文件已经变得相当头痛。
I have this situation in my project and solving class definition related errors crossing over several header files has become quite a headache.
推荐答案
:
- 将实现与接口配对。如果你有
foo.cxx
,那里定义的一切最好在foo.h
中声明。 - 确保每个头文件#包含独立编译所需的所有其他必要的头文件或前缀声明。
- 抵制创建全部头文件的诱惑。
- 将一组相关(且相互依赖)的功能放入单个文件中。 Java和其他环境鼓励每个文件一个类。使用C ++,您通常每个文件需要一个类类。
- 如果可能,优先于
#include
的转发声明。这允许您断开循环标头依赖关系。基本上,对于跨单独文件的循环依赖,你想要一个文件依赖图看起来像这样:
-
A.cxx
需要Ah
和Bh
-
B.cxx
需要Ah
和Bh
-
Ah
需要Bh
-
Bh
是独立的(并且向前声明Ah
中定义的类)
- Pair up your interfaces with implementations. If you have
foo.cxx
, everything defined in there had better be declared infoo.h
. - Ensure that every header file #includes all other necessary headers or forward-declarations necessary for independent compilation.
- Resist the temptation to create an "everything" header. They're always trouble down the road.
- Put a set of related (and interdependent) functionality into a single file. Java and other environments encourage one-class-per-file. With C++, you often want one set of classes per file. It depends on the structure of your code.
- Prefer forward declaration over
#include
s whenever possible. This allows you to break the cyclic header dependencies. Essentially, for cyclical dependencies across separate files, you want a file-dependency graph that looks something like this:A.cxx
requiresA.h
andB.h
B.cxx
requiresA.h
andB.h
A.h
requiresB.h
B.h
is independent (and forward-declares classes defined inA.h
)
如果您的代码是其他开发人员使用的库,则还需要执行一些重要的步骤:
If your code is intended to be a library consumed by other developers, there are some additional steps that are important to take:
- 如有必要,使用private headers的概念。也就是说,几个源文件需要的头文件,但公共接口从不需要。这可以是具有常用内联函数,宏或内部常量的文件。
- 在文件系统级别将您的公共接口与私有实现分开。我倾向于在我的C或C ++项目中使用
include /
和src /
子目录,其中include /
有我所有的公共头,src /
有我所有的来源。和私人标题。
- If necessary, use the concept of "private headers". That is, header files that are required by several source files, but never required by the public interface. This could be a file with common inline functions, macros, or internal constants.
- Separate your public interface from your private implementation at the filesystem level. I tend to use
include/
andsrc/
subdirectories in my C or C++ projects, whereinclude/
has all of my public headers, andsrc/
has all of my sources. and private headers.
我建议查找John Lakos的书大型C ++软件设计。这是一本相当丰富的书,但如果你只是浏览一些关于物理建筑的讨论,你会学到很多东西。
I'd recommend finding a copy of John Lakos' book Large-Scale C++ Software Design. It's a pretty hefty book, but if you just skim through some of his discussions on physical architecture, you'll learn a lot.
这篇关于C ++类的头文件组织的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-