views:

175

answers:

6

Hi

say you have a source file named sum.c that looks like this:

#include "sum.h"

int sum(int x, int y) {
    return x+y;
}

What's the point of including method's header in it's own definition file? Aren't you supposed to include it only in source files that call the sum function?

+9  A: 

If you don't include the header file, you will not be able to use the sum method in other methods that are declared before in the same file.

Konamiman
+10  A: 

This way you avoid possible problems if the definitions in the header and in the source files differ.

sharptooth
+5  A: 

It's good practice to do that in C simply because a decent compiler should highlight differences between the function's prototype and the implementation. Not to mention that in more complex examples, you might also declare, say, a struct or similar in the header file that your function needs. You don't want to duplicate this, so you include the header file.

Timo Geusch
A: 

The header may define some types or macros that are useful for the implementation. It's better to get these from the header than to duplicate them.

Pascal Cuoq
+1  A: 

It depends on what you define in the header file. If for example you have some type or macro definitions that need to be accessed both by the sum.c functions and external files, then you need to include it everywhere.

You may also want to have two header files per source file. A private one, included only by sum.c. This will contain things only needed by sum.c functions and the purpose of it is to increase code readability.

The second "public" header file will contain the things needed by callers of the sum.c functions. You don't need to include this in the sum.c file.

kgiannakakis
A: 

The source file "sum.c" has the definition for the function sum(); the Declaration of the function "sum()" is included in the headerfile "sum.h".This helps maintain the readability.

Jyothi Sangam