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:
- 如果需要,可以使用私有头的概念。也就是说,头由几个源文件必需的,但从来没有通过公共接口所需的文件。这可能是与普通的内联函数,宏或内部常数的文件。
- 从在文件系统级别您的私人执行分开的公共接口。我倾向于使用
包含/
和的src /
在我的C或C ++项目,子目录,其中包括/
有我所有的公共头和的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.
我建议你找约翰洛科什出版的书的大型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屋!
-