条件编译的一个作用

条件编译的一个作用

 

条件编译的一个作用是用于处理文件之间的关系。使其在同一个文件中不被重复包含。

如果文件的关系是这样:

   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");

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值