Main Content

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

Objects or functions with external linkage shall be declared in a header file

Description

Rule Definition

Objects or functions with external linkage shall be declared in a header file.

Rationale

If you declare a function or object in a header file, it is clear that the function or object is meant to be accessed in multiple translation units. If you intend to access the function or object from a single translation unit, reduce its visibility in other translation units by declaring the object as static or in an unnamed namespace.

Polyspace Implementation

Polyspace® reports a violation of this rule if you declare an object or function with external linkage outside of a header file. These objects and functions have external linkage when they are declared at the namespace level, unless they are part of an explicitly unnamed namespace:

  • Functions not declared static

  • Non-const variables not declared static

  • Variables declared extern

  • Enumerations

  • Names of classes, class member functions, static data members

  • Names of nested class and enumerations

  • Names of friend functions declared within the class body

Functions and extern objects declared at a block scope also have external linkage.

For details about which objects and functions have external linkage, see Storage class specifiers.

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:

  • decls.h:

    extern int x;
  • file.cpp:

    #include "decls.h"
    
    int x = 0;
    int y = 0; //Noncompliant
    static int z = 0;

The variables x and y have external linkage, but only x is declared in a header file. Polyspace reports a violation for the declaration of the external variable y outside of a header file.

The variable z is declared with the static specifier and does not have external linkage. Declaring it outside of a header file is compliant with this rule.

Check Information

Group: Basic Concepts
Category: Required

Version History

Introduced in R2013b