简单头文件
何谓简单?即我们头文件不会出现重复
头文件相信大家都不陌生
#include <stdio.h>
#include <stdlib.h>
#include <bits/stdc++.h>
…
其实,我们也可以自己来创造头文件,并且,我们写的函数都可以当作我们的头文件来存放,这样,我们的程序看上去会更美观
直接看样本
#include <bits/stdc++.h>
using namespace std;
#include "add.h"
int main()
{
int a=5;
int b=7;
int ans;
ans=add(a,b);
cout << ans << endl ;
return 0;
}
在这个代码中,我们发现并没有add函数,仔细观察后我们发现,头文件有个#include “add.h” ,这是个什么呢
其实,我们是把add函数的内容放在了这个头文件里面,相当与把函数内容折叠了起来
注意我们这里不是用的< >而是用的" “,因为只有系统自带的头文件才能用< >,而我们自己写的头文件需要用” "。
这个代码完全等价于下面这个代码
#include <bits/stdc++.h>
using namespace std;
int add(int x,int y) //展开
{
return x+y;
}
int main()
{
int a=5;
int b=7;
int ans;
ans=add(a,b);
cout << ans << endl ;
return 0;
}
怎么实现把函数放入头文件?
很简单
我们以codeblocks为例
当我们写好main文件并标记好头文件后,
我们点击File
之后我们将鼠标指向New,再在子叶中点击Empty file(空文件)
(之后会出来一个选项框,选择“是”)
我们先确定我们project的名字,在计算机中找到并点开这个文件夹
我们将文件名改成add.h 类型C/C++ 点击保存
我们会发现我们左边多了一点header(头文件),也会多一个空的待写程序
我们将函数的内容写在这里
之后我们运行这个project就可以了!
总之,头文件不同于宏定义,它没有花里胡哨,就是把头文件这个文件里的内容完全不变地搬到我们的main文件里面来,我们之前用到的系统头文件也是一样,它就是从系统文件里搬过来。
.
.
.
复杂头文件
在一些比较大的project中,头文件中可能会镶嵌其他的头文件,这就可能会出现重复,我们就需要一个保护代码
#ifndef
code
main.c
#include <stdio.h>
#include <stdlib.h>
#include "fx.h"
int main()
{
int a;
a=200;
a=add(a,1);
printf("%d\n",a);
return 0;
}
fx.h
#ifndef FX_H_INCLUDED //如果还没有声明这个函数
#define FX_H_INCLUDED
int add(int a,int b);
#endif // FX_H_INCLUDED
fx.c
#include <stdio.h> //不同.c的头文件是独立的
int add(int a,int b)
{
int ans;
ans=a+b;
printf("ok\n");
return ans;
}