C语言 如何创建C头文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2831361/
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
How can I create C header files
提问by user340838
I want to be able to create a collection of functions in a header file that I could #include in one of my C Programs.
我希望能够在头文件中创建一组函数,我可以在我的一个 C 程序中#include。
回答by Pablo Santa Cruz
- Open your favorite text editor
- Create a new file named whatever.h
- Put your function prototypes in it
- 打开你最喜欢的文本编辑器
- 创建一个名为whatever.h的新文件
- 将您的函数原型放入其中
DONE.
完毕。
Example whatever.h
示例whatever.h
#ifndef WHATEVER_H_INCLUDED
#define WHATEVER_H_INCLUDED
int f(int a);
#endif
Note: include guards (preprocessor commands) added thanks to luke. They avoid including the same header file twice in the same compilation. Another possibility (also mentioned on the comments) is to add #pragma oncebut it is not guaranteed to be supported on every compiler.
注意:包括由于 luke 添加的守卫(预处理器命令)。它们避免在同一个编译中两次包含相同的头文件。另一种可能性(也在评论中提到)是添加,#pragma once但不保证每个编译器都支持它。
Example whatever.c
示例whatever.c
#include "whatever.h"
int f(int a) { return a + 1; }
And then you can include "whatever.h" into any other .c file, and link it with whatever.c's object file.
然后您可以将“whatever.h”包含到任何其他 .c 文件中,并将其与whatever.c 的目标文件链接。
Like this:
像这样:
sample.c
样本.c
#include "whatever.h"
int main(int argc, char **argv)
{
printf("%d\n", f(2)); /* prints 3 */
return 0;
}
To compile it (if you use GCC):
编译它(如果你使用 GCC):
$ gcc -c whatever.c -o whatever.o
$ gcc -c sample.c -o sample.o
To link the files to create an executable file:
要链接文件以创建可执行文件:
$ gcc sample.o whatever.o -o sample
You can test sample:
您可以测试样品:
$ ./sample
3
$
回答by Bryan Ash
Header files can contain any valid C code, since they are injected into the compilation unit by the pre-processor prior to compilation.
头文件可以包含任何有效的 C 代码,因为它们在编译之前由预处理器注入到编译单元中。
If a header file contains a function, and is included by multiple .cfiles, each .cfile will get a copy of that function and create a symbol for it. The linker will complain about the duplicate symbols.
如果头文件包含一个函数,并且被多个.c文件包含,则每个.c文件都将获得该函数的副本并为其创建一个符号。链接器会抱怨重复的符号。
It is technically possible to create staticfunctions in a header file for inclusion in multiple .cfiles. Though this is generally not done because it breaks from the convention that code is found in .cfiles and declarations are found in .hfiles.
技术上可以static在头文件中创建函数以包含在多个.c文件中。虽然这通常不会这样做,因为它违反了在.c文件中找到代码而在文件中找到声明的约定.h。
See the discussions in C/C++: Static function in header file, what does it mean?for more explanation.
参见C/C++:头文件中的静态函数中的讨论,是什么意思?更多解释。

