Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages/Disadvantages of Header Files

Tags:

java

c++

c

header

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?

like image 895
Jeff Linahan Avatar asked Mar 27 '11 21:03

Jeff Linahan


2 Answers

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.

like image 195
Jon Avatar answered Sep 20 '22 13:09

Jon


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.

like image 38
irreputable Avatar answered Sep 23 '22 13:09

irreputable