主要内容

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

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

using-directives and using-declarations (excluding class scope or function scope using-declarations) shall not be used in header files

描述

规则定义

using-directives and using-declarations (excluding class scope or function scope using-declarations) shall not be used in header files. 1

理由

如果头文件中存在 using 指令或声明,则包含头文件的顺序可能会影响最终的程序结果。确保程序行为不依赖于头文件的包含顺序是一种良好的编程实践。

Polyspace 实现

检查项在头文件中标记 using 指令或声明。

故障排除

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

示例

全部展开

头文件:headerUnits.h

void checkValueForOverflows(int32_t);

namespace Units {
    void checkValueForOverflows(int8_t);
}

inline void convertToAcceptedUnit(int8_t originalValue) {
    checkValueForOverflows(originalValue);
}

头文件:headerAcceptedUnits.h

namespace Units {
    
}

using namespace Units; //Noncompliant

包含前两个头文件的源文件:

#include <cstdint>
#include "headerUnits.h"
#include "headerAcceptedUnits.h"

int8_t convert(int8_t meterReading) {
    convertToAcceptedUnit(meterReading);
}

在此示例中,头文件 headerAcceptedUnits.h 中的 using 指令暴露了命名空间 Units。此指令与头文件中的内嵌函数一起,使 headerUnits.hheaderAcceptedUnits.h 的包含顺序对最终程序的执行变得很重要。

  • 如果 headerAcceptedUnits.h 包括在 headerUnits.h 之前,则函数 convertToAcceptedUnit() 调用函数 checkValueForOverflows(int32_t)

  • 如上所示,如果 headerAcceptedUnits.h 包括在 headerUnits.h 之后,则函数 convertToAcceptedUnit() 将调用函数 checkValueForOverflows(int8_t)

检查信息

组:声明
类别:必需

版本历史记录

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