谁能从头到尾用一个简单的例子解释如何在C中创建一个头文件?
#ifndef MY_HEADER_H
# define MY_HEADER_H
//put your function headers here
#endif
MY_HEADER_H用作双包含保护。
对于函数声明,只需要定义签名,即不需要参数名,如下所示:
int foo(char*);
如果你真的想,你也可以包含参数的标识符,但这不是必要的,因为标识符只会在函数体(实现)中使用,而在头(参数签名)的情况下,它是缺失的。
这声明了函数foo,它接受char*类型并返回int类型。
在您的源文件中,您将有:
#include "my_header.h"
int foo(char* name) {
//do stuff
return 0;
}
foo。
#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;
}
c
#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
头文件包含在.c或.cpp/文件中定义的函数的原型。CXX文件(取决于你使用的是c还是c++)。你想在你的.h代码周围放置#ifndef/#定义,这样如果你在程序的不同部分包含了两次相同的.h,原型只包含一次。
client.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,如下所示:
client.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;
}
myfile.h
#ifndef _myfile_h
#define _myfile_h
void function();
#endif
myfile c。
#include "myfile.h"
void function() {
}