What is the point of header files in C? [duplicate]

Solution 1:

Header files are needed to declare functions and variables that are available. You might not have access to the definitions (=the .c files) at all; C supports binary-only distribution of code in libraries.

Solution 2:

The compiler needs the information in the header files to know what functions, structures, etc are available and how to use them.

All languages needs this kind of information, although they retrieve the information in different ways. For example, a Java compiler does this by scanning either the class-file or the java source code to retrieve the information.

The drawback with the Java-way is that the compiler potentially needs to hold a much more of information in its memory to be able to do this. This is no big deal today, but in the seventies, when the C language was created, it was simply not possible to keep that much information in memory.

Solution 3:

The main reason headers exist is to share declarations among multiple source files.

Say you have the function float *f(int a, int b) defined in the file a.c and reused in b.c and d.c. To allow the compiler to properly check arguments and return values you either put the function prototype in an header file and include it in the .c source files or you repeat the prototype in each source file.

Same goes for typedef etc.

While you could, in theory, repeat the same declaration in each source file, it would become a real nightmare to properly manage it.

Some language uses the same approach. I remember the TurboPascal units being not very different. You would put use ... at the beginning to signal that you were going to require functions that were defined elsewhere. I can't remember if that was passed into Delphi as well.

Solution 4:

  1. Know what is in a library at your disposal.
  2. Split the program into bite-size chunks for the compiler. Compiling a megabyte of C files simultaneously will take more resources than most modern hardware can offer.
  3. Reduce compiler load. Why should it know in screen display procedures about deep database engine? Let it learn only of functions it needs now.
  4. Separate private and public data. This use isn't frequent but you may implement in C what C++ uses private fields for: each .c file includes two .h files, one with declarations of private stuff, the other with whatever others may require from the file. Less chance of a namespace conflict, safer due to hermetization.
  5. Alternate configs. Makefile decides which header to use, and the same code may service two different platforms given two different header files.

probably more.