Main Content

MISRA C++:2023 Rule 6.0.3

The only declarations in the global namespace should be main, namespace declarations and extern "C" declarations

Since R2024b

Description

Rule Definition

The only declarations in the global namespace should be main, namespace declarations and extern "C" declarations.

Rationale

Adhering to this rule avoids name clashes. Failure to keep namespaces clean can result in reuse of a name or shadowing of a name, leading to compilation errors, linking errors, or unexpected results.

If you define an alias with the using directive in the global namespace, the alias is not added to the global namespace. Similarly, names declared in an inline namespace are not added to the global namespace. Because these uses can make it appear as if the names are added to the global namespace, this rule prohibits the use of inline namespace and the using directive in the global namespace.

Polyspace Implementation

Polyspace® reports a violation of this rule if the global namespace contains anything other than these:

  • main

  • namespace declarations

  • statements enclosed in extern "C" declarations

Polyspace reports violations if you put extern declarations in a local scope.

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 violate 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
}

using namespace ns_foo;         //Noncompliant
using ns_foo::bar;              //Noncompliant

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 the global variable var1

  • Declaration of the non-extern function foo(), in the global namespace

  • Declaration of aliases using the using directive in the global namespace.

  • Declaration of the extern function foo3() in a nonglobal namespace.

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

Check Information

Group: Basic concepts
Category: Advisory

Version History

Introduced in R2024b