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

标签 c gcc include c-preprocessor header-files

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

你好.h

void hello (const char * name);

你好.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 包含它自身 的定义你好 (const char * name) ,我的意思是它不会从外部提供?

谢谢

最佳答案

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

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

void hello (int notCorrect) { ... }

到您的 C 源文件中,它会愉快地独立编译这两个源文件,然后(取决于您在 ... 位中实际执行的操作)在运行时失败。


例如,考虑文件:

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 对现在不一致)。


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


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

关于c - 为什么在已经定义函数的源代码中添加头文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54452961/

相关文章:

c - 仅使用算术运算符将美元金额排序为 20/10/5/1(无循环)

c++ - 使用 D3D12Device 调用 DuplicateOutput 失败并出现 E_NOINTERFACE

c - 如果通过限制指针发生,实现是否可以优化对非原子访问的原子访问?

C/C++ 中的编译时位运算

c - 将内容存储在数组中并显示

c++ - 如何使用 __attribute__((visibility ("default")))?

windows - 在 Windows 上使用 OpenSSL 编译 cUrl,缺少 -lcrypto 和 -lssl

c++ - 如何在 Fedora 的 C++ 中包含 avcodec.h

c++ - 我应该在 C++ 程序中包含 <xxxx.h> 或 <cxxxx> 吗?

jsp - JSP 片段如何将其依赖项包含到父级的 head 标记中?