两种防止头文件重复包含的方法
一 头文件重复包含可能会产生错误
编译时报错,num重复定义了:
[root@ansible9 ~]# gcc main.c
In file included from main.c:3:
b.h:1:5: error: redefinition of ‘num’
int num=10;
^~~
In file included from a.h:1,
from main.c:2:
b.h:1:5: note: previous definition of ‘num’ was here
int num=10;
^~~
二 方法一: #pragma once
使用方法:将#pragma once每个头文件的最上方
编译执行成功:
[root@ansible9 ~]# gcc main.c
[root@ansible9 ~]# ./a.out
num=10
特点:
这种方法是由编译器来支持的,所以老的编译器可能不支持
三 方法二: ifndef
使用方法:在每个头文件用下面格式来防重复
#ifndef 宏名
#define 宏名
头文件内容
#endif
[root@ansible9 ~]# cat main.c a.h b.h
# include <stdio.h>
#include "a.h"
#include "b.h"
int main(int argc, char *argv[])
{
printf("num=%d\n",num);
return 0;
}
#ifndef __A_H__
#define __A_H__
#include "b.h"
#endif
#ifndef __B_H__
#define __B_H__
int num=10;
#endif
编译执行结果:
[root@ansible9 ~]# gcc main.c
[root@ansible9 ~]# ./a.out
num=10