Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do i need to include a .h header file in the .c file of the same name?

Tags:

c

So I'm following along in Head First C and we're on a chapter where we learn to compile multiple files together. One of them is encrypt.c.

#include "encrypt.h"


void encrypt(char *message)
{
  char c;
  while (*message) {
   *message = *message ^ 31;
   message++;
  }
}

The encrypt.h file repeats the first line with a semicolon at the end, so why do I need it? I understand why I would need header files to fix the problem of using a function before it's defined, so I could understand #including it in a file that uses encrypt.c, but why would I need it inside encrypt.c? Is it just one of those "because" reasons?

like image 252
punstress Avatar asked Aug 25 '13 21:08

punstress


1 Answers

If the contents of encrypt.c are shown in their entirety, then you don't need the header. But it's still a good idea to include it because:

  1. If one function in the file uses another, then the order of definition matters because the callee must be defined before the caller. It's even possible to have two functions A and B where each calls the other, in which case you cannot get the code to compile without at least one forward declaration. Including the header with the forward declarations solves these problems.
  2. Consuming the header just like your client code does is a good way to have the compiler point out discrepancies between the signatures in the forward declarations and the actual function definitions. If undetected this kind of problem can lead to "interesting" behavior at runtime and lots of hair-pulling.
like image 190
Jon Avatar answered Oct 09 '22 22:10

Jon