简体   繁体   English

合并头文件和cpp文件

[英]Merging header file and cpp file

I'm working on a C++ project where I've implemented every class as a separate .h file and .cpp file. 我正在一个C ++项目中,在该项目中,我将每个类都实现为单独的.h文件和.cpp文件。 I'm finding out this wasn't worth the hassle. 我发现这不值得麻烦。 - I'm editing back and forth between two files - It caused me a lot of unsuspected headaches (having to add predeclaration, explicitly export templated classes) - I don't see a direct benefit, my code base is bound to stay relatively small (say < 10,000 lines of code) and compilation time isn't substantial. -我正在两个文件之间来回编辑-这使我感到很多头疼(必须添加预声明,显式导出模板类)-我没有看到直接的好处,我的代码库一定会保持相对较小(例如<10,000行代码)和编译时间并不多。

My question is two fold 我的问题有两个

a) Is there a benefit I might have missed in keeping implementation and prototype separated? a)我可能会错过将实现与原型分离的好处吗?

b) If not, is there any free tool or ide that has the capability of merging a cpp file back into the header file? b)如果没有,是否有任何免费工具或ide能够将cpp文件合并回头文件?

Don't do this. 不要这样 For most simple classes, where you want to expose the class for use somewhere else, you should always* have the declaration of the class in a .h header file, and the definition (code) in a .cpp file. 对于大多数简单的类,要在其他地方公开使用该类,则应始终*在.h头文件中包含该类的声明,并在.cpp文件中包含该定义(代码)。

You then include the .h file wherever you want to use the class (ie. instantiate it). 然后,您可以在要使用该类的任何位置包括.h文件(即,实例化它)。 However, the linker is responsible for "linking" the code up after each .cpp is compiled separately. 但是,链接器负责在分别编译每个.cpp之后将代码“链接”起来。

My question for you would be, "how else would you do it?" 我对您的问题是,“您还会怎么做?” One mistake I see many n00bs make is to #include "foo.c . Then what happens is, not only do you lose the independent compilation, you run into problems at link-time because there are multiple definitions of the same class . Remember, when you #include a file, it literally plops in the body of that file where you say. 我看到很多n00b犯的一个错误是#include "foo.c 。然后发生的是,不仅会丢失独立的编译,而且在链接时会遇到问题,因为同一类有多个定义。记住,当您#include一个文件时,它实际上会在您所说的文件正文中蠕动。

[*] There are of course exceptions to this rule: [*]此规则当然有例外:

One exception to this is for template classes . 一个例外是模板类 These have to be in a header file in their entirety. 这些必须全部放在头文件中。 The reason is because the actual code is not generated until the class is instantiated with a type parameter. 原因是因为在使用类型参数实例化该类之前,不会生成实际代码。 Then, the compiler essentially "fills-in" the body of the class with the specified type where required. 然后,编译器实质上在需要的地方用指定的类型“填充”了类的主体。 Since the type is not known until then, it cannot be compiled independently and linked-up later. 由于该类型直到那时才是未知的,因此无法独立编译并在以后链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM