MISRA C:2012 Dir 4.10
Precautions shall be taken in order to prevent the contents of a header file being included more than once
説明
命令の定義
Precautions shall be taken in order to prevent the contents of a header file being included more than once 1 .
根拠
入れ子にされたヘッダー ファイルの複雑な階層が翻訳単位に含まれる場合、特定のヘッダー ファイルが 2 回以上インクルードされ、混乱の原因になる可能性があります。複数回のインクルードにより複数の定義または定義の競合が生じる場合、プログラムで未定義の動作または誤動作が発生する可能性があります。
たとえば、ヘッダー ファイルに以下が含まれるとします。
#ifdef _WIN64 int env_var; #elseif long int env_var; #endif
_WIN64 を定義するパスと定義解除するパス) に含まれる場合、env_var の定義の競合が発生する可能性があります。Polyspace 実装
コンテンツが複数回のインクルードからガードされていないヘッダー ファイルをインクルードする場合、解析ではこの命令への違反を報告します。違反は、ヘッダー ファイルの最初に示されます。
複数回のインクルードからヘッダー ファイルのコンテンツをガードするための方法がいくつかあります。たとえば、プリプロセッサ命令 ifdef または ifndef をインクルード ガードとして使用します。
<start-of-file>
#ifndef <control macro>
#define <control macro>
/* Contents of file */
#endif
<end-of-file><start-of-file>
#ifdef <control macro>
#error ...
#else
#define <control macro>
/* Contents of file */
#endif
<end-of-file>トラブルシューティング
ルール違反を想定していてもその違反が表示されない場合、コーディング規約違反が想定どおりに表示されない理由の診断を参照します。
例
チェック情報
| グループ: Code design |
| カテゴリ: 必要 |
| AGC カテゴリ: 必要 |
バージョン履歴
R2014b で導入
1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.
The MISRA coding standards referenced in the Polyspace® Bug Finder™ documentation are from the following MISRA standards:
MISRA C:2004
MISRA C:2012
MISRA C:2023
MISRA C++:2008
MISRA C++:2023
MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.