Preprocessors - C Interview Questions II


Q. How can you avoid including a header more than once?
One easy technique to avoid multiple inclusions of the same header is to use the #ifndef and #definepreprocessor directives. When you create a header for your program, you can #define a symbolic name that is unique to that header. You can use the conditional preprocessor directive named #ifndef to check whether that symbolic name has already been assigned. If it is assigned, you should not include the header, because it has already been preprocessed. If it is not defined, you should define it to avoid any further inclusions of the header. The following header illustrates this technique:
#ifndef _FILENAME_H
#define _FILENAME_H
#define VER_NUM      "1.00.00"
#define REL_DATE     "08/01/94"
#if __WINDOWS__
#define OS_VER       "WINDOWS"
#else
#define OS_VER       "DOS"
#endif
#endif
When the preprocessor encounters this header, it first checks to see whether _FILENAME_H has been defined. If it hasn't been defined, the header has not been included yet, and the _FILENAME_H symbolic name is defined. Then, the rest of the header is parsed until the last #endif is encountered, signaling the end of the conditional #ifndef _FILENAME_H statement. Substitute the actual name of the header file for "FILENAME" in the preceding example to make it applicable for your programs.

Q. Can a file other than a .h file be included with #include?
The preprocessor will include whatever file you specify in your #include statement. Therefore, if you have the line
#include <macros.inc>
in your program, the file macros.inc will be included in your precompiled program. It is, however, unusual programming practice to put any file that does not have a .h or .hpp extension in an #include statement. You should always put a .h extension on any of your C files you are going to include. This method makes it easier for you and others to identify which files are being used for preprocessing purposes.
For instance, someone modifying or debugging your program might not know to look at the macros.inc file for macro definitions. That person might try in vain by searching all files with .h extensions and come up empty. If your file had been named macros.h, the search would have included the macros.h file, and the searcher would have been able to see what macros you defined in it.

Comments