C语言 头文件中是否需要函数原型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20180734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are function prototypes needed in header files?
提问by Bennett Yeo
I am programming in robotc which is just c programming with add-ins (follows all c rules). In order to organize my code I have put my subroutines in header files and are referencing from my main c document. Can I still reference the methods in the header files from the c document without putting function prototypes in the headers?
我正在用robotc 编程,这只是带有插件的c 编程(遵循所有c 规则)。为了组织我的代码,我将我的子例程放在头文件中,并从我的主 c 文档中引用。我是否仍然可以从 c 文档中引用头文件中的方法而不将函数原型放在头文件中?
For example:
例如:
Code in main1.c
main1.c 中的代码
#include header1.h
task main()
{
header_method();
}
Code in header1.h (no function prototypes)
header1.h 中的代码(无函数原型)
header_method()
{
//do stuffs
}
Or do I have to do this:
或者我必须这样做:
void header_method();
header_method()
{
//do stuffs
}
The reason is that I can only declare a certain amount of global variables for my robot in robotc.
原因是我只能在robotc中为我的机器人声明一定数量的全局变量。
回答by Keith Thompson
You should (almost) never put function definitionsin header files, as you've done in your header1.h.
您应该(几乎)永远不要将函数定义放在头文件中,就像您在header1.h.
Header files should contain function declarations(prototypes).
头文件应该包含函数声明(原型)。
(A "prototype" is a function declaration that specifies the types of the arguments. There are non-prototype function declarations that don't specify argument types, but they're obsolescent and there's no reason to use them.)
(“原型”是指定参数类型的函数声明。有些非原型函数声明不指定参数类型,但它们已经过时,没有理由使用它们。)
Function definitions(with the {... }code that implements the function) should be in .cfiles.
函数定义(带有实现函数的{...}代码)应该在.c文件中。
Each .cfile should have a #includedirective for any functions that it calls or defines.
每个.c文件都应该有一个#include指令,用于它调用或定义的任何函数。
And each header file should be protected from multiple inclusion by include guards.
并且每个头文件都应该通过包含保护来保护不被多次包含。
The idea is that each function declarationappears exactly once in each translation unit(each source file that you compile), and each function definitionappears exactly once in your entire program.
这个想法是每个函数声明在每个翻译单元(您编译的每个源文件)中只出现一次,并且每个函数定义在整个程序中只出现一次。
If you have a function that's used in only one .cfile, you can put its declaration and definition in the same .cfile (and you should probably define it as static). In fact, if the definition appears before any calls, you can omit the separate declaration; the definition itself acts as a declaration.
如果您有一个仅在一个.c文件中使用的函数,您可以将其声明和定义放在同一个.c文件中(您可能应该将其定义为static)。实际上,如果定义出现在任何调用之前,则可以省略单独的声明;定义本身充当声明。
(Functions defined as inlinecan complicate this model a bit; I suggest not worrying about that for now.)
(定义为 的函数inline会使这个模型变得有点复杂;我建议现在不要担心。)

