简体   繁体   中英

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

For example if I have the following three files written in 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);
}

I know that adding the line #include "hello.h" to the hello.c tells the compiler that the definition of hello (const char * name) will be supplied during an external file (separate compilation) , but my question now why it is added to the file hello_fn.c at the time hello_fn.c contain it self the definition of hello (const char * name) , I mean it will not be supplied from outside ?

Thanks

This is actually good practice since the compiler can check your declaration (in the header) against your definition (in hello_fn.c ).

Without that, there is no way to ensure that they match. You could quite easily put:

void hello (int notCorrect) { ... }

into your C source file and it would happily compile the two source files independently and then (depending on what you actually do in the ... bit) fail spectacularly at run-time.


For example, consider the files:

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);

This compiles fine because each C source file is internally consistent in what it states. The hello.c/hello.h pair thinks that hello takes an int while hello_fn.c thinks it takes a C string.

I get a core dump (1) when running, because the value 42 is not a valid string address. When I uncomment the include line in hello_fn.c , the compiler complains (rightly) that my declaration and definition disagree (because the hello_fn.c/hello.h pair is now inconsistent).


On top of that, there may be other stuff in the header (though not in your example case) that exists only in the header. This is typically declarations that are shared amongst caller and callee, such as types, extern items, #define items and so on. It makes little sense to declare them separately in the header and source file.


(1) Actual results may vary since this is undefined behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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