0

On most tutorial I could find on the web I have notice that everyone is creating header files for everything and never include a .c file.

I couldn't find any good explanation on the web about why you need the header file.

I have read that including the header file allows you to not repeat yourself which doesn't make sense to me. The header file IS a repetition of all the declaration of your implementation, if you include your implementation directly, then you avoid this overhead right!?!

Don't get me wrong, I can understand the use of header file when you are doing libraries : Several project can include only the header file and then linking to the same library (e.g. the standard library) thus ending up with a smaller executable. I just don't see the benefit of header file when you include something which is completly specific to your project...

Can you explain me the real benefit of header files?

tibo
  • 5,326
  • 4
  • 37
  • 53

1 Answers1

2

Suppose you have a program built from 10 source files. If each one included all the code that was needed (including, presumably, the implementations of the standard C library functions it uses), you'd have lots and lots of multiple definition errors when you link all the bits together.

So, a header (normally) includes just the declarations. The object code for the corresponding source code is linked with the program, either as explicit object files or as libraries. This stops you getting multiple definition errors.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • This is correct, but I feel like it doesn't explain the reasons enough because one could argue that you can compare the declarations (from the definitions) against a list of known declarations and then if it's a repeating one you either compare the definition and only throw an error if it's different or you skip it completely assuming it's a repeat. This of course creates a new set of problems... But the question remains open from the OPs perspective. – user2802841 Nov 24 '14 at 01:26
  • @user2802841: See the duplicate for a better discussion. – Jonathan Leffler Nov 24 '14 at 01:27
  • @JonathanLeffler Aren't include guards should actually avoid this kind of errors? – tibo Nov 24 '14 at 02:34
  • @tibo: Not really. Unless you are going to create a single source file for the entire application (see SQLite for an example of that technique), you will create multiple object files that are linked together. But each object file is the result of a single translation unit, TU. Include guards prevent multiple definition within a single TU, but do nothing to prevent repetition in multiple separate TUs. – Jonathan Leffler Nov 24 '14 at 02:37
  • @JonathanLeffler Got it! I guess my question should then "What the point of having several TU?". Here is the answer : http://en.wikipedia.org/wiki/Single_Compilation_Unit ! – tibo Nov 24 '14 at 02:43