为什么在方法定义文件中包含标头?

发布于 2024-08-13 17:01:39 字数 196 浏览 3 评论 0原文

假设您有一个名为 sum.c 的源文件,如下所示:

#include "sum.h"

int sum(int x, int y) {
    return x+y;
}

在其自己的定义文件中包含方法的标头有什么意义?难道你不应该只将它包含在调用 sum 函数的源文件中吗?

say you have a source file named sum.c that looks like this:

#include "sum.h"

int sum(int x, int y) {
    return x+y;
}

What's the point of including method's header in it's own definition file? Aren't you supposed to include it only in source files that call the sum function?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

黯然 2024-08-20 17:01:39

这样,如果标头和源文件中的定义不同,您就可以避免可能出现的问题。

This way you avoid possible problems if the definitions in the header and in the source files differ.

冷心人i 2024-08-20 17:01:39

如果不包含头文件,则无法在同一文件中之前声明的其他方法中使用 sum 方法。

If you don't include the header file, you will not be able to use the sum method in other methods that are declared before in the same file.

看轻我的陪伴 2024-08-20 17:01:39

在 C 中这样做是一个很好的做法,因为一个好的编译器应该突出显示函数原型和实现之间的差异。更不用说在更复杂的示例中,您还可以在函数需要的头文件中声明一个结构或类似结构。您不想重复此内容,因此包含头文件。

It's good practice to do that in C simply because a decent compiler should highlight differences between the function's prototype and the implementation. Not to mention that in more complex examples, you might also declare, say, a struct or similar in the header file that your function needs. You don't want to duplicate this, so you include the header file.

娇妻 2024-08-20 17:01:39

这取决于你在头文件中定义的内容。例如,如果您有一些需要由 sum.c 函数和外部文件访问的类型或宏定义,那么您需要在任何地方都包含它。

您可能还希望每个源文件有两个头文件。私有的,仅由 sum.c 包含。这将包含 sum.c 函数所需的内容,其目的是提高代码可读性。

第二个“公共”头文件将包含 sum.c 函数的调用者所需的内容。您不需要将其包含在 sum.c 文件中。

It depends on what you define in the header file. If for example you have some type or macro definitions that need to be accessed both by the sum.c functions and external files, then you need to include it everywhere.

You may also want to have two header files per source file. A private one, included only by sum.c. This will contain things only needed by sum.c functions and the purpose of it is to increase code readability.

The second "public" header file will contain the things needed by callers of the sum.c functions. You don't need to include this in the sum.c file.

空城旧梦 2024-08-20 17:01:39

标头可以定义一些对实现有用的类型或宏。
从标题中获取这些比复制它们更好。

The header may define some types or macros that are useful for the implementation.
It's better to get these from the header than to duplicate them.

清秋悲枫 2024-08-20 17:01:39

源文件“sum.c”具有函数 sum() 的定义;
函数“sum()”的声明包含在头文件“sum.h”中。这有助于保持可读性。

The source file "sum.c" has the definition for the function sum();
the Declaration of the function "sum()" is included in the headerfile "sum.h".This helps maintain the readability.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文