必须在 C 中声明函数原型吗? [英] Must declare function prototype in C?

查看:43
本文介绍了必须在 C 中声明函数原型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 C 有点陌生(我之前有 Java、C# 和一些 C++ 经验).在 C 中,是否需要声明函数原型或者没有它可以编译代码?这样做是好的编程习惯吗?还是仅仅依赖于编译器?(我正在运行 Ubuntu 9.10 并在 Code::Blocks IDE 下使用 GNU C 编译器或 gcc)

I am kind of new to C (I have prior Java, C#, and some C++ experience). In C, is it necessary to declare a function prototype or can the code compile without it? Is it good programming practice to do so? Or does it just depend on the compiler? (I am running Ubuntu 9.10 and using the GNU C Compiler, or gcc, under the Code::Blocks IDE)

推荐答案

在 ANSI C(即 C89 或 C90)中,您不必声明函数原型;但是,最好使用它们.该标准允许您不使用它们的唯一原因是为了与非常旧的代码向后兼容.

In ANSI C (meaning C89 or C90), you do not have to declare a function prototype; however, it is a best practice to use them. The only reason the standard allows you to not use them is for backward compatibility with very old code.

如果你没有原型,而你调用了一个函数,编译器会从你传递给函数的参数中推断出一个原型.如果稍后在同一编译单元中声明该函数,并且该函数的签名与编译器猜测的不同,则会出现编译错误.

If you do not have a prototype, and you call a function, the compiler will infer a prototype from the parameters you pass to the function. If you declare the function later in the same compilation unit, you'll get a compile error if the function's signature is different from what the compiler guessed.

更糟糕的是,如果函数在另一个编译单元中,则无法获得编译错误,因为没有原型就无法检查.在这种情况下,如果编译器出错,如果函数调用在堆栈上推送与函数预期不同的类型,您可能会得到未定义的行为.

Worse, if the function is in another compilation unit, there's no way to get a compilation error, since without a a prototype there's no way to check. In that case, if the compiler gets it wrong, you could get undefined behavior if the function call pushes different types on the stack than the function expects.

约定是始终在与包含函数的源文件同名的头文件中声明原型.

Convention is to always declare a prototype in a header file that has the same name as the source file containing the function.

在 C99 或 C11 中,标准 C 要求在调用任何函数之前在范围内进行函数声明.许多编译器在实践中不会强制执行此限制,除非您强制它们这样做.

In C99 or C11, standard C requires a function declaration in scope before you call any function. Many compilers do not enforce this restriction in practice unless you force them to do so.

这篇关于必须在 C 中声明函数原型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆