What are the advantages and disadvantages of using header files in a language like C or C++ verses a language like Java? I think classes should be designed from the outside in, so it is nice to have header files and not have to wade through implementation details. However, then again, each function declaration is duplicated across two files. If C and C++ were invented today would they use header files? Is this mechanism outdated or necessary?
Taken from a related blog post by Eric Lippert, who puts it very well:
I would have asked the equivalent question why does C++ need header files? Header files seem like a huge potential point of failure; all the time I edit C++ code and change the signature of a method; if I forget to update the header file, then the code doesn’t compile and often gives some cryptic error message. Hopefully this large cost actually buys you something.
It buys the compiler writer one thing, and the user one thing.
What it buys the user is that you can compile each individual “cpp” file into a “obj” file independently, provided that you have all the necessary headers. All the information necessary to generate the bodies that are in a given cpp file can be gleaned from the set of headers. This means that the build system can recompile just those cpp files that changed, provided that no header changed.
What it buys the compiler writer is that every file can be compiled in “one pass”. Because every type and method declaration is processed before its first usage, the compiler can simply start from the top of the file, pull in all the included headers, and proceed from the top down, spitting out the obj file as it goes, never having to go back and revisit something its seen already.
This is in contrast to languages such as C# (about which the blog post is) and Java, which is a pretty close relative.
It's still a good idea to separate interface and implementation. But it doesn't have to be physical separation. In Java you can see the interface from javadoc. Java IDEs usually can display API structures, and they can fold blocks. There is no compelling reasons that require physical separation. C was invented decades ago so we don't need to pick on it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With