It’s okay to put structure declarations in a header file because they don’t create variables; they just tell the compiler how to create a structure variable when you declare one in a source code file. Similarly, template declarations aren’t code to be compiled; they are instructions to the compiler on how to generate function definitions to match function calls found in the source code. Data declared const and inline functions have special linkage properties (described shortly) that allow them to be placed in header files without causing problems.
Listings 9.1, 9.2, and 9.3 show the result of dividing Listing 7.12 into separate parts. Note that you use "coordin.h" instead of
Figure 9.1 outlines the steps for putting this program together on a Unix system. Note that you just give the CC compile command, and the other steps follow automatically. The g++ and gpp command-line compilers and the Borland C++ command-line compiler (bcc32.exe) also behave that way. Apple Xcode, Embarcadero C++ Builder, and Microsoft Visual C++ go through essentially the same steps, but, as outlined in Chapter 1, you initiate the process differently, using menus that let you create a project and associate source code files with it. Note that you only add source code files, not header files, to projects. That’s because the #include directive manages the header files. Also you shouldn’t use #include to include source code files because that can lead to multiple declarations.
Figure 9.1. Compiling a multifile C++ program on a Unix system.
Caution
In IDEs, don’t add header files to the project list and don’t use #include to include source code files in other source code files.
Listing 9.1. coordin.h
// coordin.h -- structure templates and function prototypes
// structure templates
#ifndef COORDIN_H_
#define COORDIN_H_
struct polar
{
double distance; // distance from origin
double angle; // direction from origin
};
struct rect
{
double x; // horizontal distance from origin
double y; // vertical distance from origin
};
// prototypes
polar rect_to_polar(rect xypos);
void show_polar(polar dapos);
#endif
Header File Management
You should include a header file just once in a file. That might seem to be an easy thing to remember, but it’s possible to include a header file several times without knowing you did so. For example, you might use a header file that includes another header file. There’s a standard C/C++ technique for avoiding multiple inclusions of header files. It’s based on the preprocessor #ifndef (for
#ifndef COORDIN_H_
...
#endif
Normally, you use the #define statement to create symbolic constants, as in the following:
#define MAXIMUM 4096
But simply using #define with a name is enough to establish that a name is defined, as in the following:
#define COORDIN_H_
The technique that Listing 9.1 uses is to wrap the file contents in an #ifndef:
#ifndef COORDIN_H_
#define COORDIN_H_
// place include file contents here
#endif