nvillec
nvillec

Reputation: 71

Why don't I have to include my header files when compiling with GCC?

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!

Upvotes: 2

Views: 433

Answers (2)

Olaf Dietsche
Olaf Dietsche

Reputation: 74098

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'

6.5.2.2 Function calls
6 If the expression that denotes the called function has a type that does not include a prototype,
...
If the number of arguments does not equal the number of parameters, the behavior is undefined.

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.

...
If the function is defined with a type that does not include a prototype, and the types of the arguments after promotion are not compatible with those of the parameters after promotion, the behavior is undefined, ...

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.

Upvotes: 4

cnicutar
cnicutar

Reputation: 182734

When using a function without a prototype the compiler makes certain assumptions about its return type and the parameters it takes. In this case these assumptions happen to be work, even if it assumes the function returns an int.


As Eric Postpischil notes in the comments, omitting the prototype is highly discouraged as it can lead to subtle bugs. You should always make sure your function calls have the needed prototypes available, preferably by including their corresponding headers.

Upvotes: 4

Related Questions