Oli*_*rth 276
foo.h中
#ifndef FOO_H_ /* Include guard */
#define FOO_H_
int foo(int x); /* An example function declaration */
#endif // FOO_H_
Run Code Online (Sandbox Code Playgroud)
foo.c的
#include "foo.h" /* Include the header (not strictly necessary here) */
int foo(int x) /* Function definition */
{
return x + 5;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
使用GCC编译
gcc -o my_app main.c foo.c
Run Code Online (Sandbox Code Playgroud)
Fla*_*ius 24
#ifndef MY_HEADER_H
# define MY_HEADER_H
//put your function headers here
#endif
Run Code Online (Sandbox Code Playgroud)
MY_HEADER_H
作为一个双重包容卫.
对于函数头,您只需要定义签名,即不带参数名称,如下所示:
int foo(char*);
Run Code Online (Sandbox Code Playgroud)
如果你真的想要,你也可以包含参数的标识符,但这不是必需的,因为标识符只能用在函数体(实现)中,如果是标题(参数签名),它就会丢失.
这声明了foo
接受a char*
并返回一个的函数int
.
在源文件中,您将拥有:
#include "my_header.h"
int foo(char* name) {
//do stuff
return 0;
}
Run Code Online (Sandbox Code Playgroud)
myfile.h
#ifndef _myfile_h
#define _myfile_h
void function();
#endif
Run Code Online (Sandbox Code Playgroud)
myfile.c文件
#include "myfile.h"
void function() {
}
Run Code Online (Sandbox Code Playgroud)
头文件包含您在.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 */
Run Code Online (Sandbox Code Playgroud)
然后你在.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;
}
Run Code Online (Sandbox Code Playgroud)