大纲
- 头文件的作用
- 驱动文件和头文件中该存放什么内容
- 如何防止重复定义
- 头文件使用案例
1.头文件的作用
(1) 为其他驱动文件(.c)或者头文件(.h)调用相关函数、结构体、数组、全局变量等
(2)最常用的就是调用API接口(openCV、QT中的相关模板)
2. 驱动文件和头文件中该存放什么内容?
- 驱动文件(.h)存放对外调用的函数,数组、结构体、变量等申明(全局变量extern)
- 头文件(.c)存放 定义函数、数组、结构体、变量的初始化等等,static函数或变量。
- 注:一般不要在头文件中定义变量、函数、类,否者容易产生重复定义
3.如何防止重复定义
重复定义是调用别人的库函数时变量被重新申明。
如: 在a.h 中申明变量 extern int a;
在b.h 中申明变量 extern int a;
这时候: 在c.c中调用 a.h 和 b.h , 就会出现 xxxx has been defined .
头文件使用案例(1):不涉及重复定义
//a.c
//#include<stdio.h>
void print(void)
{
printf(“test\n”);
}
//a.h
extern void print(void);
//b.c
#include<a.h>
main()
{
print();
}
after compiled, print test.
头文件使用案例(2):涉及重复定义
我们在使用头文件定义时候,如定义结构体在头文件中定义,在头文件中申明全局
或者在驱动文件中定义,在头文件中申明全局变量。
本案例定义结构体变量,然后初始化结构体,然后在主函数中调用结构体函数实现相应功能。
//1.struct.h
#ifndef __a_H_
#define __a_H_
typedef struct
{
unsigned char i;
unsigned char u;
unsigned char v;
} check;
#endif
//2. xxx.c
初始化结构体
#include<struct.h>
void initalstruct(check* AAA)
{
AAA->i =3;
AAA->u =4;
AAA->v =5;
}
// xxx.h
extern void initalstruct(check* AAA);
#include<stdio.h>
#include<struct.h> //定义结构体
#include<xxx.h> //调用结构体初始化函数
int main()
{
check check1;
initalstruct(&check1);
printf(“%d\n”,check1.i );
}
拖延让你失去很多,并且那些是再也回不去的昨天。
初心 initial heart start in 2021 11 10
Date:2021-11-10