在C中创建自己的头文件

Anu*_*eb3 164 c header include-guards include c-header

任何人都可以通过一个简单的例子从头到尾解释如何在C中创建头文件.

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)

  • @Jeyekomon:嗯,哪里*是*问题? (5认同)
  • 值得注意的是,如果您尝试通过按钮构建它(例如,在Code :: Blocks中"构建并运行"),则此代码不起作用.对你来说这似乎是显而易见的,但对我来说这是它第一次发生,我花了很长时间才弄明白问题出在哪里. (3认同)
  • @Anu:我不能用这种格式阅读.您可以编辑原始问题以包含此代码. (2认同)
  • 没有人告诉我,“构建并运行”按钮并不足以满足所有需求。:-)这对我来说是一个惊喜(我是新手)。现在,我想我必须先学习使用命令行或makefile。 (2认同)

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)


Tom*_*n32 8

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)


djs*_*dog 5

头文件包含您在.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)