Question:

How can you avoid including a header more than once?

Answer:

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.


Keywords:

© 2017 QuizBucket.org