条件编译的一个作用
条件编译的一个作用是用于处理文件之间的关系。使其在同一个文件中不被重复包含。
如果文件的关系是这样:
A
/ \
C D
\ /
B
上面的文件有关系,C中包含A,D中包含A。 B中要包括C和D,这样条件编译就可把在预处理阶段去掉重复包含文件A。
$ cattest1.h
#ifndef__A__H__
#define__A__H__
int i =0
voidmyprint();
#endif
chenwl@jftest$~
$ cattest3.h
#ifndef__TEAT3__H__
#define__TEAT3__H__
#include"test1.h"
#endif
chenwl@jftest$~
$ cattest4.h
#ifndef__TEST4__H__
#define__TEST4__H__
#include"test1.h"
#endif
Test3.c文件:
#include<stdio.h>
#include"test3.h"
#include"test4.h"
intmain(){
printf("%d\n",i);
printf("hello world\n");
}
看看gcc -o test3.E -E test3.c 预处理的结果
# 2"test3.c" 2
# 1"test3.h" 1
# 1"test1.h" 1
int i=0;
voidmyprint();
# 4"test3.h" 2
# 3"test3.c" 2
# 1"test4.h" 1
# 4"test3.c" 2
intmain(){
printf("%d\n",i);
printf("hello world\n");
}
编译通过,int I =0 和voidmyprint()只出现一次。
把test1.h文件中的条件编译去掉。
//#ifndef__A__H__
//#define__A__H__
int i=0;
voidmyprint();
//#endif
编译报错:
test1.h:3:5:error: redefinition of 'i'
test1.h:3:5:note: previous definition of 'i' was here
再看gcc -o test3.E -E test3.c 结果:
有两个int i =0; void myprint(); 重复定义了。
# 2"test3.c" 2
# 1"test3.h" 1
# 1"test1.h" 1
int i =0;
void myprint();
# 4"test3.h" 2
# 3"test3.c" 2
# 1"test4.h" 1
# 1"test1.h" 1
int i=0;
voidmyprint();
# 4"test4.h" 2
# 4"test3.c" 2
intmain(){
printf("%d\n",i);
printf("hello world\n");
}