Re: C++ header file
- From: "Alex Blekhman" <tkfx.REMOVE@xxxxxxxxx>
- Date: Sat, 10 Nov 2007 02:00:26 +0200
<worlman385@xxxxxxxxx> wrote:
Why C++ need header file stores interface (list of function) of a CPP
file?
Why not just have 1 CPP file and include the CPP file instead of
header file?
In Java, there is no header file, each object is .java file.
For each CPP file, there must be a header file map to it.
Is the header file is more analogy to Java's JavaDoc that describe
each member inside a Class?
In addition to the answers of others. Contrary to Java, C++ (and C, as well) may have separate declaration and definition of types and functions. You can declare a type/function in one file, but define (implement) it elsewhere. Usually, a developer puts declarations in header file. Then he implements a function in one of CPP files.
Header file itself cannot be compiled. It is included in other CPP file. Then all #include directives are expanded by preprocessor and the whole thing (it is called "translation unit") is fed to the compiler.
Separation of declaration and definition is very practical thing. It allows you to compile function's definition, which is placed in CPP file, only once. All other CPP files that call this function can be compiled separately. It is sufficient to see only function's declaration in order to successfully compile a code that calls it.
You could place all your code solely in CPP files and then include them one into another. After all, preprocessor doesn't care about file's extension. However, it will produce larger OBJ file with the same redundant code multiplied across many OBJ files. In the past linkers were really stupid, so they just were leaving all the redundant dead code there. So, the ability to separate declaration and definition was important. Today linkers are much smarter, they can remove unused code, so the problem is not that acute anymore.
HTH
Alex
.
- References:
- C++ header file
- From: worlman385
- C++ header file
- Prev by Date: Re: O_TEXT in microsoft environment
- Next by Date: Re: Automatic variable
- Previous by thread: Re: C++ header file
- Next by thread: O_TEXT in microsoft environment
- Index(es):
Relevant Pages
|