主要内容

本页采用了机器翻译。点击此处可查看最新英文版本。

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

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

描述

规则定义

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

理由

该规则确保在全局范围内找到的所有名称都是命名空间的一部分。遵守此规则可避免名称冲突,并确保开发人员不会重用变量名称,从而导致编译/链接错误,或遮盖变量名称,导致以后可能出现意外问题。

Polyspace 实现

除了 main 函数外,检查项会标记全局范围内使用但不属于命名空间的所有名称。

如果名称在 extern "C" 模块(C++ 代码中的 C 代码)中声明,检查项不会在全局范围内标记这些名称。但是,如果您使用选项忽略链接错误 (-no-extern-c),这些名称也会被标记。

故障排除

如果您预期会出现违规,而 Polyspace® 未报告该违规,请参阅诊断为何编码规范违规未按预期显示

示例

全部展开

此示例显示了全局命名空间中违反此规则的名称。

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

在此示例中,Polyspace 将以下内容报告为违反此规则:

  • 在全局命名空间中声明变量,例如 var1

  • 在全局命名空间中声明非 extern 函数,例如 foo

  • 在非全局命名空间中声明 extern 函数。

此规则不适用于本地命名空间中的非 extern 名称。

检查信息

组:声明
类别:必需

版本历史记录

在 R2013b 中推出


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.