有人可以解释一下如何从头到尾创建一个C头文件的简单示例吗?
有人可以解释一下如何从头到尾创建一个C头文件的简单示例吗?
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
make
,您(可能)仍将使用gcc
或cc
,并且仍需要告诉make
告诉任一编译器需要哪些文件。为什么您希望避免向编译器提供“foo.c”? - eenblam#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;
}
#include
包含它。例如,标准库的函数就是在像<stdio.h>
这样的头文件中声明的。” - Jonathan Wakely我的文件.h
#ifndef _myfile_h
#define _myfile_h
void function();
#endif
我的文件.c
#include "myfile.h"
void function() {
}
void function();
as a declaration does not prevent calls like function(42);
. Use void
in the declaration like void function(void);
- chux - Reinstate Monicavoid function();
允许这样做,因为这是早期 C 的风格,其中一个 声明 实际上只是告诉函数名存在和返回类型。 - chux - Reinstate Monica头文件包含了你在 .c 或 .cpp/.cxx 文件中定义的函数原型(取决于你使用的是 c 还是 c++)。你需要在你的 .h 代码周围放置 #ifndef/#define,这样如果你在程序的不同部分两次包含同一个 .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;
}
foo.c
)的源代码中没有使用#ifndef
和#define
指令,而是在该库的头文件中使用?这是因为编译器知道它只有一个实际的定义foo.c
吗? - simchuck