谁能从头到尾用一个简单的例子解释如何在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() {
}
推荐文章
- time_t最终的类型定义是什么?
- 我需要显式处理负数或零时,总和平方数字?
- 函数名周围的括号是什么意思?
- 用C语言创建自己的头文件
- 格式化IO函数(*printf / *scanf)中的转换说明符%i和%d之间的区别是什么?
- main()中的Return语句vs exit()
- 如果不是内存地址,C指针到底是什么?
- 我如何在Visual Studio中预处理后看到C/ c++源文件?
- 保护可执行文件不受逆向工程的影响?
- 从C语言的函数返回一个struct
- C99 'restrict'关键字的实际用法?
- 检查子字符串存在于C中的字符串中
- 从标准输入中捕获字符,而不需要等待按enter键
- 查找当前可执行文件的路径,不包含/proc/self/exe
- 如何创建可变参数宏(参数数量可变)