Main Content

MISRA C++:2008 Rule 3-2-3

A type, object or function that is used in multiple translation units shall be declared in one and only one file

Description

Rule Definition

A type, object or function that is used in multiple translation units shall be declared in one and only one file.

Rationale

If you declare an identifier in a header file, you can include the header file in any translation unit where the identifier is defined or used. In this way, you ensure consistency between:

  • The declaration and the definition.

  • The declarations in different translation units.

This rule recommends declaring external objects or functions in header files. This way, the compiler can detects incompatible types of the same entity that is perhaps declared inadvertently.

Polyspace Implementation

Polyspace® reports a violation of this rule if you declare an extern object in multiple files.

Troubleshooting

If you expect a rule violation but Polyspace does not report it, see Diagnose Why Coding Standard Violations Do Not Appear as Expected.

Examples

expand all

This example uses two files:

  • file1.cpp:

    #include "header.hpp"
    extern int flag;//Noncompliant
    class A{/**/};
    void foo(void){
    	//..
    } 
  • header.hpp:

    extern int flag;

The external identifier flag is declared in both header.hpp and file1.cpp. Polyspace reports a violation of this rule.

Check Information

Group: Basic Concepts
Category: Required

Version History

Introduced in R2013b