0

When I program in c there are .h files . Header files contain the signatures of functions that are implement in c files.

Why are header files are needed as I can include the c file to use the function there instead of using headers.

Is this to make the compiler's job easier?

HardcoreHenry
  • 5,909
  • 2
  • 19
  • 44
  • For the most part, yes, it's to make the compiler's job easier. C was created decades ago, when computer time was much more valuable compared to human time. – Lee Daniel Crocker Aug 20 '19 at 19:40
  • Which c file will you include to get a definition of `fopen`? – William Pursell Aug 20 '19 at 20:04
  • 1
    Header files is the mechanism used by the language to allow sharing of information between two different C files. Compilation generally takes a long time compared to linking, so we often split the source code into separate C files to allow them to be compiled separately. That way, if we need to change one part of the software, only the affected C files need to be recompiled, not all of the code. Sometimes, distinct C files need some shared declarations in order to interface with each other. Header files allow this sharing without resorting to compiling a large source file. – jxh Aug 20 '19 at 20:15
  • Including C files amounts to creating a large source file. Also, if you don't manage it properly, you will probably create duplicate definitions. You want to share declarations, not definitions. – jxh Aug 20 '19 at 20:17

1 Answers1

1

TLDR answer is organization and code reuse.

Header files contain common standard code usable across multiple code bases - think of them as libraries to bring in.

This code is kept separate for maintenance issues. You only want one copy, so when a fix needs making it happens in one place. All of the various code bases you have that reference that one included header file suddenly have the updates.

You can also do project specific headers. For example, my SQL statements are all static strings, since they are long and complex I keep them in a different file and just include it. This way, I don't have a large long blob of complex SQL as a string in the middle of my code.

ivanivan
  • 2,155
  • 2
  • 10
  • 11