It was my understanding that in order to use a function declared in a header file and defined in a matching source file, said header file must be included before main(). So why does the following compile and run just fine using:
gcc -o hello hellomain.c hello.c
hellomain.c
int main(int argc, char *argv[])
{
helloPrint();
return 0;
}
hello.h
#ifndef hello_h
#define hello_h
void helloPrint();
#endif
hello.c
#include <stdio.h>
void helloPrint()
{
printf("Hello, World!");
}
This is obviously a very simplified example but it illustrates my question; why don’t I have to include “hello.h” in “hellomain.c”? Thanks!
When you use an undeclared function in a C source file, the compiler derives the parameters from the call and assumes a return type of int.
According to ISO Standard ‘Programming Languages – C’
This means, when you use a function without declaring it and the number of your arguments and the number of actual parameters of the function disagree, all bets are off.
Also, when you use a function without declaring it and the types of your arguments and the actual types of the function don’t match, anything might happen.
So, although it might work in some cases, you should declare the functions you use in your program. If you don’t, the compiler cannot help and detect mismatches between function declarations and function calls.