Main Content

MISRA C++:2023 Rule 6.5.2

Internal linkage should be specified appropriately

Since R2024b

Description

Rule Definition

Internal linkage should be specified appropriately.

Rationale

To comply with this rule:

  • Specify the internal linkage of an identifier unambiguously by declaring the identifier in an anonymous namespace.

  • Do not:

    • Use the static keyword to specify internal linkage. The static keyword has other uses and using it to specify internal linkage can be ambiguous.

    • Declare or redeclare identifiers declared in an anonymous namespace with the extern keyword. Identifiers declared in an anonymous namespace have internal linkage. If you redeclare them using the extern keyword, the compiler ignores the keyword the code can be confusing to read.

Polyspace Implementation

Polyspace® reports a violation of this rule if any of these are true:

  • You declare an identifier in an anonymous namespace by using either the static or extern keywords.

  • You declare a namespace-scope const, constexpr, or inline variable outside an anonymous namespace. Namespace-scope const, constexpr, or inline variables have internal linkage. To comply with this rule, declare such variables in anonymous namespaces.

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

In this example, Polyspace reports violations of this rule when you specify the internal linkage of a variable inappropriately:

  • The namespace-cope const variables constGlobal and constnamed are declared outside an anonymous namespace. These namespace-scope const variables have internal linkage, but they are not declared in an anonymous namespace. Polyspace reports violations.

  • The global identifiers staticGlobal and foo() are specified to have internal linkage by using the static keyword, which is an ambiguous way of specifying internal linkage. Polyspace reports violations.

  • The variables ambiguousStatic and ambiguousExtern are declared in an anonymous namespace and have internal linkage. However, they are declared using keywords static and extern that make their linkage difficult to determine. Polyspace reports a violation.

int const constGlobal; //Noncompliant
static int staticGlobal; //Noncompliant

namespace {
	static int ambiguousStatic; //Noncompliant
	extern int ambiguousExtern; //Noncompliant
	int UnabiguousInternal;//Compliant

}

namespace Name {
	int const constNamed; //Noncompliant
}

static int foo(int); //Noncompliant

Check Information

Group: Basic Concepts
Category: Advisory

Version History

Introduced in R2024b