Main Content

AUTOSAR C++14 Rule M7-3-3

There shall be no unnamed namespaces in header files

Description

Rule Definition

There shall be no unnamed namespaces in header files.

Rationale

According to the C++ standard, names in an unnamed namespace, for instance, aVar:

namespace {
   int aVar;
}
have internal linkage by default. If a header file contains an unnamed namespace, each translation unit with a source file that #include-s the header file defines its own instance of objects in the namespace. The multiple definitions are probably not what you intended and can lead to unexpected results, unwanted excess memory usage, or inadvertently violating the one-definition rule.

Polyspace Implementation

The checker flags unnamed namespaces in header 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

Header File: aHeader.h

namespace { //Noncompliant
   int aVar;
}

First source file: aSource.cpp

#include "aHeader.h"
#include <iostream>

void setVar(int arg) {
    std::cout << "Current value: " << aVar << std::endl;
    aVar = arg;
    std::cout << "Value set at: " << aVar << std::endl;
}

Second source file: anotherSource.cpp

#include "aHeader.h"
#include <iostream>

extern void setVar(int);

void resetVar() {
    std::cout << "Current value: " << aVar << std::endl;
    aVar = 0;
    std::cout << "Value set at: 0" << std::endl;
}

void main() {
    setVar(1);
    resetVar();
}

In this example, the noncompliant unnamed namespace leads to two definitions of aVar in the translation unit from aSource.cpp and the translation unit from anotherSource.cpp. The two definitions can lead to possible unexpected output:

Current value: 0
Value set at: 1
Current value: 0
Value set at: 0

Check Information

Group: Declaration
Category: Required, Automated

Version History

Introduced in R2019a