谁能用一个简单的例子从头到尾解释如何在 C 中创建头文件。
问问题
378701 次
4 回答
348
foo.h
#ifndef FOO_H_ /* Include guard */
#define FOO_H_
int foo(int x); /* An example function declaration */
#endif // FOO_H_
foo.c
#include "foo.h" /* Include the header (not strictly necessary here) */
int foo(int x) /* Function definition */
{
return x + 5;
}
主程序
#include <stdio.h>
#include "foo.h" /* Include the header here, to obtain the function declaration */
int main(void)
{
int y = foo(3); /* Use the function here */
printf("%d\n", y);
return 0;
}
使用 GCC 编译
gcc -o my_app main.c foo.c
于 2011-08-18T15:31:51.793 回答
31
#ifndef MY_HEADER_H
# define MY_HEADER_H
//put your function headers here
#endif
MY_HEADER_H
用作双重包含保护。
对于函数声明,只需要定义签名,即不带参数名,像这样:
int foo(char*);
如果你真的想要,你也可以包含参数的标识符,但这不是必需的,因为标识符只会在函数的主体(实现)中使用,如果是标头(参数签名),它会丢失。
这声明foo
了接受 achar*
并返回a的函数int
。
在您的源文件中,您将拥有:
#include "my_header.h"
int foo(char* name) {
//do stuff
return 0;
}
于 2011-08-18T15:31:50.693 回答
10
我的文件.h
#ifndef _myfile_h
#define _myfile_h
void function();
#endif
我的文件.c
#include "myfile.h"
void function() {
}
于 2011-08-18T15:34:11.100 回答
8
头文件包含您在 .c 或 .cpp/.cxx 文件中定义的函数的原型(取决于您使用的是 c 还是 c++)。您想在 .h 代码周围放置 #ifndef/#defines,这样如果您在程序的不同部分包含两次相同的 .h,则原型仅包含一次。
客户端.h
#ifndef CLIENT_H
#define CLIENT_H
short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);
#endif /** CLIENT_H */
然后你会在 .c 文件中实现 .h ,如下所示:
客户端.c
#include "client.h"
short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
short ret = -1;
//some implementation here
return ret;
}
于 2011-08-18T15:32:27.410 回答