Why do I need C header files?

This is a stupid question, I admit. The code will explain this better. Got these files:

hello.c:

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

main.c:

 int main() { hello("world!"); return 0; } 

Makefile:

 test : main.o hello.o gcc -o test main.o hello.o main.o : main.c gcc -c main.c hello.o : hello.c gcc -c hello.c .PHONY : clean clean : -rm test -rm main.o -rm hello.o 

I can just do and .test, and it works. Should I include something like hello.h in main.c so that the compiler knows the function prototype?

I haven't even turned on hello.c anywhere, and it just works! Why does main.c know about the hello function?

If this works, when do I need .h files? I am new to C programming, but I thought this concept was easy to understand, now I'm completely confused.

+4
source share
2 answers

If you use the -Wall flag (and should always be used with -Werror -Wextra ), you will receive the following message:

 main.c: In function 'main': main.c:3: warning: implicit declaration of function 'hello' 

And the compiler effectively "guesses" what to do, which can lead to disaster in many circumstances.

Proper use of header files avoids these kinds of warnings.

+13
source

You do not need header files; instead, your functions need prototypes. When you call hello , passing it "world" , C shows that you are calling a function with one argument, taking char* , and doing everything right. However, this will not work if the function accepts a float, and you decide to stroke it int (try it, it is very instructive). For backward compatibility reasons, C will allow you to call functions without prototypes, but this is dangerous. For example, in the case of your call to hello compiler considers that you are calling a function that returns an int . Technically, you invoke undefined behavior, so your program runs randomly.

The headers seem to provide the most convenient way to deliver prototypes, but you can provide them in the code itself, for example:

 void hello(char*); int main() { hello("world!"); return 0; } 
+4
source

All Articles