There is nothing magic about compilation. Nor automatic!
Header files basically provide information to the compiler, almost never code.
That information alone, is usually not enough to create a full program.
Consider the "hello world" program (with the simpler puts
function):
#include <stdio.h>
int main(void) {
puts("Hello, World!");
return 0;
}
without the header, the compiler does not know how to deal with puts()
(it is not a C keyword). The header lets the compiler know how to manage the arguments and return value.
How the function works, however, is not specified anywhere in this simple code. Somebody else has written the code for puts()
and included the compiled code in a library. The code in that library is included with the compiled code for your source as part of the compilation process.
Now consider you wanted your own version of puts()
int main(void) {
myputs("Hello, World!");
return 0;
}
Compiling just this code gives an error because the compiler has no information about the function. You can provide that information
int myputs(const char *line);
int main(void) {
myputs("Hello, World!");
return 0;
}
and the code now compiles --- but does not link, ie does not produce an executable, because there is no code for myputs()
. So you write the code for myputs()
in a file called "myputs.c"
#include <stdio.h>
int myputs(const char *line) {
while (*line) putchar(*line++);
return 0;
}
and you have to remember to compile both your first source file and "myputs.c" together.
After a while your "myputs.c" file has expanded to a hand full of functions and you need to include the information about all the functions (their prototypes) in the source files that want to use them.
It is more convenient to write all the prototypes in a single file and #include
that file. With the inclusion you run no risk of making a mistake when typing the prototype.
You still have to compile and link all the code files together though.
When they grow even more, you put all the already compiled code in a library ... and that's another story :)