繁体   English   中英

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

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

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

你好

void hello (const char * name);

你好ç

#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 (const char * name)的定义时将其添加到文件hello_fn.c中,我的意思是不会从外部提供它吗?

谢谢

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

没有这些,就无法确保它们匹配。 您可以很容易地提出:

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.cinclude hello_fn.c ,编译器会(正确地)抱怨我的声明和定义不同意(因为hello_fn.c/hello.h对现在不一致)。


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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM