C源文件包含其自己的头文件有什么好处 [英] What's the benefit for a C source file include its own header file

查看:129
本文介绍了C源文件包含其自己的头文件有什么好处的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,如果源文件需要引用其他文件的功能,那么它需要包含其头文件,但是我不明白为什么源文件包含其自己的头文件。头文件中的内容只是在每个处理时间内作为函数声明被复制并粘贴到源文件中。对于包含其自己的头文件的源文件,这样的声明在我看来似乎不是必需的,实际上,从源文件中删除头后,项目仍然可以编译并且链接没有问题,所以源文件包括它的原因是什么?

I understand that if a source file need to reference functions from other file then it needs to include its header file, but I don't understand why the source file include its own header file. Content in header file is simply being copied and pasted into the source file as function declarations in per-processing time. For source file who include its own header file, such "declaration" doesn't seem necessary to me, in fact, project still compile and link no problem after remove the header from it's source file, so what's the reason for source file include its own header?

推荐答案

主要好处是让编译器验证您的标头及其实现的一致性。您这样做是因为它很方便,而不是因为它是必需的。如果没有这样的包含,肯定有可能使项目正确编译并运行,但是从长远来看,这会使项目的维护复杂化。

The main benefit is having the compiler verify consistency of your header and its implementation. You do it because it is convenient, not because it is required. It may definitely be possible to get the project to compile and run correctly without such inclusion, but it complicates maintenance of your project in the long run.

如果文件没有如果包含其自己的标头,则可能会偶然遇到函数的前向声明与该函数的定义不匹配的情况-可能是因为您添加或删除了一个参数,而忘记了更新标头。发生这种情况时,仍将依赖于具有不匹配功能的代码进行编译,但是调用将导致未定义的行为。最好让编译器捕获此错误,该错误会在源文件包含其自己的标头时自动发生。

If your file does not include its own header, you can accidentally get in a situation when forward declaration of a function does not match the definition of the function - perhaps because you added or removed a parameter, and forgot to update the header. When this happens, the code relying on the function with mismatch would still compile, but the call would result in undefined behavior. It is much better to have the compiler catch this error, which happens automatically when your source file includes its own header.

这篇关于C源文件包含其自己的头文件有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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