为什么在已经定义函数的源代码中添加头文件?

Why a header file is added in the source code where the function is ALREADY defined?

例如,如果我有以下三个用 C 编写的文件:

hello.h

void hello (const char * name);

hello.c

#include "hello.h"
int
main (void)
{
hello ("world");
return 0;
}

hello_fn.c

#include <stdio.h>
#include "hello.h"
void
hello (const char * name)
{
printf ("Hello, %s!\n", name);
}

我知道将行 #include "hello.h" 添加到 hello.c 告诉编译器 hello (const char * name) 的定义将在外部文件(单独编译),但我现在的问题是为什么它在 hello_fn.c 时被添加到文件 hello_fn.c 包含它自己 hello (const char * name) 的定义,我的意思是不会外供吗?

谢谢

这实际上是一个很好的做法,因为编译器可以根据您的定义(在 hello_fn.c 中)检查您的声明(在 header 中)。

否则,无法确保它们匹配。你可以很容易地输入:

void hello (int notCorrect) { ... }

到您的 C 源文件中,它会愉快地独立编译这两个源文件,然后(取决于您在 ... 位中实际执行的操作)在 run-time.[=24 处失败=]


例如,考虑以下文件:

hello.c:
    #include <stdio.h>
    #include "hello.h"
    int main(void) { hello(42); }
hello_fn.c:
    #include <stdio.h>
    //#include "hello.h"
    void hello(char *x) { puts(x); }
hello.h:
    int hello(int x);

这可以很好地编译,因为每个 C 源文件的内容在内部都是一致的。 hello.c/hello.h 对认为 hello 采用 inthello_fn.c 认为它采用 C 字符串。

我在 运行 时得到核心转储 (1),因为值 42 不是有效的字符串地址。当我取消注释 hello_fn.c 中的 include 行时,编译器(正确地)抱怨我的声明和定义不一致(因为 hello_fn.c/hello.h 对现在不一致)。


最重要的是,other 中可能存在 header 中的内容(尽管在您的示例中不存在)仅 在 header 中。这通常是在调用者和被调用者之间共享的声明,例如类型、extern 项、#define 项等。在 header 和源文件中 单独 声明它们没有什么意义。


(1) 实际 结果可能会有所不同,因为这是未定义的行为。