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. 1

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 an identifier in the global namespace using the static keyword.

This rule does not apply to const or constexpr identifiers.

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 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.


static int staticGlobal; //Noncompliant

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

}

static int foo(int); //Noncompliant

Check Information

Group: Basic Concepts
Category: Advisory

Version History

Introduced in R2024b


1 All MISRA coding rules and directives are © Copyright The MISRA Consortium Limited 2021.

The MISRA coding standards referenced in the Polyspace Bug Finder™ documentation are from the following MISRA standards:

  • MISRA C:2004

  • MISRA C:2012

  • MISRA C:2023

  • MISRA C++:2008

  • MISRA C++:2023

MISRA and MISRA C are registered trademarks of The MISRA Consortium Limited 2021.