Main Content

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

The global namespace shall only contain main, namespace declarations and extern "C" declarations

Description

Rule Definition

The global namespace shall only contain main, namespace declarations and extern "C" declarations.

Rationale

The rule makes sure that all names found at global scope are part of a namespace. Adhering to this rule avoids name clashes and ensures that developers do not reuse a variable name, resulting in compilation/linking errors, or shadow a variable name, resulting in possibly unexpected issues later.

Polyspace Implementation

Other than the main function, the checker flags all names used at global scope that are not part of a namespace.

The checker does not flag names at global scope if they are declared in extern "C" blocks (C code included within C++ code). However, if you use the option Ignore link errors (-no-extern-c), these names are also flagged.

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 shows names in the global namespace that are violates this rule.

#include <cstdint>
void foo(int32_t);                //Noncompliant
int32_t var1;                      //Noncompliant

namespace                       // Compliant
{
	void foo2(int32_t);             // Rule does not apply
	int32_t var2;                 // Rule does not apply
}

namespace ns_foo                // Compliant
{
	void bar(int32_t);             // Rule does not apply
	int32_t var3;                   // Rule does not apply
}

namespace ns_x = ns_foo;          // Compliant

int main()                      // Compliant
{
	extern void foo3();             //Noncompliant
}

In this example, Polyspace reports these as violations of this rule:

  • Declaration of variable such as var1 in

  • Declaration of non-extern functions , such as foo, in the global namespace

  • Declaration of extern functions in a nonglobal namespace.

This rule does not apply to non-extern names in local namespaces.

Check Information

Group: Declarations
Category: Required

Version History

Introduced in R2013b