[英]What sense does it make to declare a function more than one time in C?
I've seen a couple of times that the prototype declaration of a function in the header was literally repeated in the c-file. 我已经看到几次,头文件中的函数原型声明实际上在c文件中重复了。
It is possible to declare a function more than one time in C - but what sense does it make? 可以在C中多次声明一个函数-但是它有什么意义? Is it just for better readability or is there some deeper insight which I am missing?
只是为了提高可读性,还是我缺少一些更深入的见解?
It is possible. 有可能的。 It doesn't make any sense.
这没有任何意义。
But it does not cause any harm either. 但这也不会造成任何伤害。 You can declare a function as many times as you like, but each such declaration must be identical to the others.
您可以根据需要多次声明一个函数,但是每个这样的声明必须与其他声明相同。 So it is pointless to do so.
因此,这样做毫无意义。 As someone suggested, maybe it is a copy/paste error.
正如有人建议的那样,可能是复制/粘贴错误。
You can only have one function definition though, which should always be in the c file. 但是,您只能有一个函数定义 ,该函数定义应该始终在c文件中。
This is how you should do it: 这是您应该如何做:
Function declarations which is part of the caller's interface should be in the h file, and there only. 属于调用方接口的函数声明应该位于h文件中,并且仅存在于此文件中。
Function declarations of local (private) functions that are only available from inside the c file itself, should be in the c file, and there only. 仅可从c文件本身内部使用的局部(私有)函数的函数声明,应仅在c文件中,并且在那里。 Such functions should be declared and defined as
static
. 此类函数应声明并定义为
static
。
Duplicate function declarations serve no useful semantic purpose, but they may arise for historical reasons, because of local coding conventions, or for some other reason. 重复的函数声明没有任何有用的语义目的,但是它们可能由于历史原因,由于本地编码约定或某些其他原因而出现。
For example, it may be a local coding convention that every function in each source file is prototyped at the beginning of that file. 例如,可能是本地编码约定,即每个源文件中的每个函数都在该文件的开头原型化。 That has some minor practical utility, such as serving as a manifest of the functions defined in each file, and making the functions inside each file able to ignore any concern about whether other functions in the same file are declared in a header.
这具有一些次要的实用工具,例如用作每个文件中定义的功能的清单,并使每个文件中的功能能够忽略是否在标头中声明同一文件中的其他功能的任何担忧。
Additionally, multiple declarations of the same function or object don't necessarily have to be identical , they only need to be compatible . 此外,相同功能或对象的多个声明不一定必须相同 ,它们只需要兼容即可 。 Under some circumstances it may makes sense to provide a less specific prototype in a header and a more specific one in the source file containing the function definition (which itself serves as yet another declaration).
在某些情况下,在标头中提供一个不太具体的原型,而在包含函数定义(它本身又充当另一个声明)的源文件中提供一个更具体的原型可能是有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.