包含.cpp文件和.h文件的区别(cpp内容相同)? [英] Difference in including the .cpp file and .h file (with the same content in cpp)?

查看:43
本文介绍了包含.cpp文件和.h文件的区别(cpp内容相同)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始从基础开始学习 cpp,但对以下内容非常困惑:

I've recently started learning cpp from basics and was very much confused with the folowing:

假设我有一个标题(test.h,它只包含声明),其中包含一些内容和一些源文件(source.cpp),并且程序产生了一些结果.

Lets say I have a header( test.h which contains only declarations) with some content and some source file (source.cpp) and program produced some result.

如果我已将该头文件的相同内容复制到 .cpp 文件 (testcpp.cpp) 并将其包含在 source.cpp

If I have copied the same content of that header file to a .cpp file (testcpp.cpp) and included this in source.cpp

在这种情况下,我不明白它有什么区别?

In this case, I did not understood what difference it makes?

(我不会在make文件中包含这个testcpp.cpp)

(I'll not include this testcpp.cpp in make file)

我看过一些与此类似的主题,但没有明确的想法!!!

I have seen some threads similar to this but couldn't get a clear idea!!!

我学习了头文件和 cpp 文件的用法,并且到目前为止已经在项目中正确使用它,请针对这种情况做出具体的回答(我知道这样做会增加混乱,但只是想知道).这样做会有什么不同,还是只是每个人都遵循的普遍做法?

推荐答案

有什么不同?

头文件的扩展名对任何事情都没有影响.您也可以将文件命名为 test.mpg.testtest(显然更改 include 指令),它会工作也一样.扩展是为了程序员的利益,而不是为了工具链.

The extension of a header file has no effect on anything. You could have just as well named the file test.mpg, .test or just test (changing the include directive obviously), and it would have worked just as well. The extension is for the benefit of the programmer, not the toolchain.

但是,将它命名为 .h、.hpp 或任何您的约定之外的任何名称是一个坏主意.如果你把它命名为.mpg,人们会认为它是一个视频,而没有意识到它是一个头文件,试着在媒体播放器中播放它.如果您将其命名为 .cpp,人们会认为它是一个源文件,并可能会尝试对其进行编译或向其中添加定义.

However, it is a bad idea to name it anything other than .h, .hpp or whatever is your convention. If you name it .mpg, people will think that it is a video, and not realising that it is a header file, try to play it in a media player. If you name it .cpp, people will think that it is a source file and may attempt to compile it or maybe add definitions into it.

在预处理器中包含文件在技术上只是将一个文件的内容复制到另一个文件中.不多也不少.关于他们的其他一切都只是约定俗成.

Including a file with the preprocessor is technically just copying contents of one file into another. Nothing more and nothing less. Everything else about them is just convention.

在makefile中,指定源文件时,我可以给我的源文件以任何扩展名(.fsfs,.xxx)而不是.cpp扩展名

In makefile, when specifying source file, Can I give my source files with any extension(.fsfs, .xxx) rather than .cpp extension

从技术上讲是的,但是编译器通常使用源文件扩展名来检测在这种情况下它们将无法执行的语言,因此您必须明确指定它.

Technically yes, however compilers usually use the source file extension to detect the language which they will fail to do in this case, so you would have to specify it explicitly.

这篇关于包含.cpp文件和.h文件的区别(cpp内容相同)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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