开发者

Advantages/Disadvantages of Header Files

开发者 https://www.devze.com 2023-02-19 22:47 出处:网络
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 he

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 th开发者_开发百科rough 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.


Briefly, in C or C++ header files allow different files to share common definitions or declarations.

In Java everything is an object, so there's no concept of sharing anything except objects. Each object is one file; if you want to access the object, you import the file.

0

精彩评论

暂无评论...
验证码 换一张
取 消