C ++头文件和实现文件:什么包括? [英] C++ header and implementation files: what to include?

查看:199
本文介绍了C ++头文件和实现文件:什么包括?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个.h文件和一个具有相同名称但不同扩展名的.cpp文件。

There is a .h file and a .cpp file with the same name but different extension.

如果我想使用.cpp文件中的内容,我包括.h文件或.cpp文件?

If I want to use what's in the .cpp file, do I include the .h file or the .cpp file?

推荐答案

简单的答案是,你几乎总是想包括.h文件,并编译.cpp文件。 CPP文件是(通常)真正的代码,H文件(通常)是前向声明。

The simple answer is that you almost always want to include .h files, and compile .cpp files. CPP files are (usually) the true code, and H files are (usually) forward-declarations.

更长的答案是,它可能会为你工作,但两者会给出稍微不同的结果。

The longer answer is that you may be able to include either, and it might work for you, but both will give slightly different results.

include基本上是在该行复制/粘贴文件。

What "include" does is basically copy/paste the file in at that line. It doesn't matter what the extension is, it will include the contents of the file the same way.

但是,按照惯例,C ++代码通常是这样写的:

But C++ code is, by convention, usually written this way:

SomeClass.cpp -

SomeClass.cpp -

#include "SomeClass.h"
#include <iostream>

void SomeClass::SomeFunction()
{
  std::cout << "Hello world\n";
}

SomeClass.h -

SomeClass.h -

class SomeClass
{
  public:
    void SomeFunction();
};

如果包括其中任何一个,您可以使用它的代码。但是,如果您有多个包含相同.cpp文件的文件,您可能会收到关于重新定义的错误。头文件(.h文件)通常只包含前向声明,没有实现,因此在多个地方包含它们不会给你重新定义的错误。

If you include either of those, you can use the code from it. However, if you have multiple files that include the same .cpp file, you may get errors about re-definition. Header files (.h files) usually contain only forward declarations, and no implementations, so including them in multiple places won't give you errors about re-definition.

如果你不知何故设法编译没有错误,当包括.cpp文件从其他.cpp文件,你仍然可能最终与重复的代码。如果您在多个其他文件中包含相同的.cpp文件,则会发生这种情况。这就像你写函数两次。这将使你的程序在磁盘上更大,编译时间更长,运行速度更慢。

If you somehow manage to compile without errors when including .cpp files from other .cpp files, you can still end up with duplicate code. This happens if you include the same .cpp files in multiple other files. It's like you wrote the function twice. This will make your program bigger on disk, take longer to compile, and run a bit slower.

主要的警告是,这个实现/对于使用模板的代码。模板代码仍将作为.h文件传递给您,但它(通常)直接在.h文件中实现,并且不会伴随.cpp文件。

The main caveat is that this implementation/forward declaration convention doesn't hold true for code that uses templates. Template code will still be handed to you as .h files, but it (usually) is implemented directly in the .h file, and won't have accompanying .cpp files.

这篇关于C ++头文件和实现文件:什么包括?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆