f78 Inheritance and Header Files Contents|Index|Previous|Next
 

Inheritance and header files 

Inheritance is what happens when one object or file derives some of its contents by virtual copying from another object or file. In the case of C header files, inheritance means that one header file includes another header file and then replaces or adds something.

If the inheriting header file and the base header file have different names, then inheritance is straightforward: simply write #include "base" in the inheriting file.

Sometimes it is necessary to give the inheriting file the same name as the base file. This is less straightforward.

For example, suppose an application program uses the system header file sys/signal.h, but the version of /usr/include/sys/signal.h on a particular system doesn’t do what the application program expects. It might be convenient to define a local version, perhaps under the name /usr/local/include/sys/signal.h, to override or add to the one supplied by the system. Use the option, -I., for compilation, and writing a file sys/signal.h that does what the application program expects. But making this file include the standard sys/signal.h is not so easy—writing #include <sys/signal.h> in that file doesn’t work, because it includes your own version of the file, not the standard system version.

Used in that file itself, this leads to an infinite recursion and a fatal error in compilation.

#include </usr/i 8e3 nclude/sys/signal.h> would find the proper file, but that is not clean, since it makes an assumption about where the system header file is found. This is bad for maintenance, since it means that any change in where the system’s header files are kept requires a change somewhere else.

The clean way to solve this problem is to use #include_next, which means, “Include the next file with this name.” This directive works like #include except in searching for the specified file: it starts searching the list of header file directories after the directory in which the current file was found.

Suppose you specify -I /usr/local/include, and the list of directories to search also includes /usr/include; and suppose that both directories contain a file named sys/signal.h. Ordinary #include <sys/signal.h> finds the file under /usr/local/include. If that file contains #include_next <sys/signal.h>, it starts searching after that directory, and finds the file in /usr/include. 0