【发布时间】:2011-10-29 21:53:44
【问题描述】:
谁能用一个简单的例子从头到尾解释如何用C创建头文件。
【问题讨论】:
-
你读过关于 C 的介绍性书籍吗?这是一个在线的:publications.gbdirect.co.uk/c_book.
标签: c header include include-guards c-header
谁能用一个简单的例子从头到尾解释如何用C创建头文件。
【问题讨论】:
标签: c header include include-guards c-header
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;
}
main.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
【讨论】:
#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;
}
【讨论】:
extern 声明收集在一个单独的文件中,历史上称为 header,包含在 #include 中每个源文件的前面。例如,标准库的函数在像<stdio.h>这样的头文件中声明。"
我的文件.h
#ifndef _myfile_h
#define _myfile_h
void function();
#endif
我的文件.c
#include "myfile.h"
void function() {
}
【讨论】:
void function(); 作为 声明 不会阻止像 function(42); 这样的调用。在声明中使用void,如void function(void);
头文件包含您在 .c 或 .cpp/.cxx 文件中定义的函数的原型(取决于您使用的是 c 还是 c++)。您想在 .h 代码周围放置 #ifndef/#defines,这样如果您在程序的不同部分包含两次相同的 .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;
}
【讨论】:
#ifndef 和#define 指令不在库文件的源代码中使用(即上面示例中的foo.c),而不是在该库的头文件中?是因为编译器知道它只有一个foo.c 的实际定义吗?