Header file etiquette
When you create a struct
containing member functions, you are creating a new data type. In general, you
want this type to be easily accessible to yourself and others. In addition, you
want to separate the interface (the declaration) from
the implementation (the definition of the member
functions) so the implementation can be changed without forcing a re-compile of
the entire system. You achieve this end by putting the declaration for your new
type in a header file.
When I first learned to program in C, the
header file was a mystery to me.
Many C books don’t seem to emphasize it, and the compiler didn’t
enforce function declarations, so it seemed optional most of the time, except
when structures were declared. In C++ the use of header files becomes crystal
clear. They are virtually mandatory for easy program development, and you put
very specific information in them: declarations. The
header file tells the compiler what is available in your library. You can use
the library even if you only possess the header file along with the object file
or library file; you don’t need the source code for the cpp file.
The header file is where the interface specification is stored.
Although it is not enforced by the
compiler, the best approach to building large projects in C is to use libraries;
collect associated functions into the same object module or library, and use a
header file to hold all the declarations for the functions. It is de
rigueur in C++; you could throw any function into a C library, but the C++
abstract data type determines the functions that are associated by dint of their
common access to the data in a struct. Any member function must be
declared in the struct declaration; you cannot put it elsewhere. The use
of function libraries was encouraged in C and institutionalized in
C++.