头文件
头文件是我们.c文件与主函数所在文件的接口在单片机工程当中,我们常常使用模块化编程。经常使用多个.c文件。以及自己建立头文件的方式。
如何在Vc++6.0中建立头文件
- 首先我们先建立一个工程文件夹。这个就不用说了吧。
2.文件名字是xxx.h
然后双击C/C++ header file
文件就建立完成了。
分析头文件构造
我们看到有三个东西
#ifndef __my_h__
#define __my_h__
#endif
首先从英文上理解它
#ifndef
如果没有定义
#define
定义
#endif
结束如果
条件编译
如上三个东西都是属于条件编译的东西,以下都属于。
指令 用途
# 空指令,无任何效果
#include 包含一个源代码文件
#define 定义宏
#undef 取消已定义的宏
#if 如果给定条件为真,则编译下面代码
#ifdef 如果宏已经定义,则编译下面代码
#ifndef 如果宏没有定义,则编译下面代码
#elif 如果前面的#if给定条件不为真,当前条件为真,则编译下面代码
#endif 结束一个#if……#else条件编译块
#error 停止编译并显示错误信息
————————————————
为什么要使用#ifndef
这里我们结合一个实际工程来分析。看这个rule.h
有多个文件都使用了这个.h
在一个工程里如果你没有使用#ifndef,又有多个文件使用了你这个.h文件
编译器就会二次编译就会报错。
分析
第一次编译时 环境并没有#define rule.h 所以第一次时环境会执行代码中的#define
#ifndef __RULE_H__
#define __RULE_H__
#include "usart.h"
sbit bee=P2^2;
extern char time[6];
//extern char buffer[40];
extern data char Alam_Time[3][6];
extern char Config[30];
unsigned char Junge_Arr(char row[6],char in[6]);
unsigned char Junge(char row[6],char in[3][6],unsigned char i);
void Execute(char dat[3][6],unsigned char num,unsigned char i);
#endif
第二次编译这个头文件时执行到#ifndef 不满足条件 环境就不会执行#define 就不会出现二次编译的情况。
#endif
用来结束条件编译,函数的声明 全局变量的extern 都放在这个上面上面。
实验
我们随意写一个函数 这个函数写在1.c里面 将函数声明放在 my.h当中
1.c
#include "my.h"
#define Level 3
int Trans(int Data)
{
#ifdef Level
printf("I Am Define\n");
#endif
return Data-3;
}
my.h
#ifndef __my_h__
#define __my_h__
#include "stdio.h"
int Trans(int Data);
#endif
分析
#ifdef Level
printf("I Am Define\n");
#endif
如果我们定义了Level这个宏就输出
I Am Define
这条语句。
修改Level
#include "my.h"
#define Leve 3
int Trans(int Data)
{
#ifdef Level
printf("I Am Define\n");
#endif
return Data-3;
}
我们删掉一个l。可以看到代码就没有执行printf
还有其他的语句我就不一一举例子了。