主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

MISRA C:2023 Rule 17.3

A function shall not be declared implicitly

自 R2024a 起

描述

规则定义

A function shall not be declared implicitly 1 .

理由

如果在声明或定义函数之前调用函数,会发生隐式声明。如果在调用函数之前显式声明函数,编译器可以将参量和返回类型与声明中的参数类型进行匹配。如果发生隐式声明,编译器会对参量和返回类型进行假设。例如,它会假定返回类型为 int。这些假设可能与预期不符,并导致不期望的类型转换。

故障排除

如果您预计存在违规,但未看到该违规,请参阅Diagnose Why Coding Standard Violations Do Not Appear as Expected

示例

全部展开

#include <math.h>

extern double power3 (double val, int exponent);
int getChoice(void);

double func() {
    double res;
    int ch = getChoice();
    if(ch == 0) {
        res = power(2.0, 10);    /* Non-compliant */
    }
    else if( ch==1) {
        res = power2(2.0, 10);   /* Non-compliant */
    }
    else {
        res = power3(2.0, 10);   /* Compliant */
        return res;
    }
}

double power2 (double val, int exponent) {
    return (pow(val, exponent));
}

在此示例中,当代码中调用未声明的函数时,便违反了此规则。即使代码的后面部分存在函数定义,也会出现违规。

如果在代码中调用某个函数之前已声明该函数,则不会违反此规则。如果函数定义存在于另一个文件中,且仅在链接阶段可用,则可以通过以下方式之一声明该函数:

  • 在当前文件中使用 extern 关键字声明函数。

  • 在头文件中声明函数,然后在当前文件中包含此头文件。

检查信息

组:函数
类别:强制
AGC 类别:强制

版本历史记录

在 R2024a 中推出


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.