[previous] MISRA-C:2004  Rule  19.15:  (Required) [next] Precautions shall be taken in order to prevent the contents of a header file being included twice.
When a translation unit contains a complex hierarchy of nested header files it can happen that a particular header file is included more than once. This can be, at best, a source of confusion. If it leads to multiple or conflicting definitions, the result can be undefined or erroneous behaviour.

Multiple inclusions of a header file can sometimes be avoided by careful design. If this is not possible, a mechanism must be in place to prevent the file contents from being included more than once. A common approach is to associate a macro with each file; the macro is defined when the file is included for the first time and used subsequently when the file is included again to exclude the contents of the file.

For example a file called "ahdr.h" might be structured as follows:

#ifndef AHDR_H
#define AHDR_H
/* The following lines will be excluded by the
   preprocessor if the file is included more
   than once */

...

#endif

Alternatively, the following may be used.

#ifdef AHDR_H
#error Header file is already included
#else
#define AHDR_H
/* The following lines will be excluded by the
   preprocessor if the file is included more
   than once */

...

#endif


QAC messages that encompass this guideline:

0883 Include file code is not protected against repeated inclusion



(c) The Motor Industry Research Association, 2004
QA C Source Code Analyser 8.1.2
MISRA-C:2004 Compliance Module 3.2
© 2013 Programming Research
www.programmingresearch.com
Personality Groups | Glossary | Message Index | MISRA-C:2004 Rule Index Contents