c语言十二:三种条件编译


一般情况下源程序中所有行都参加编译,但有时需要对部分源程序行只在满足一定条件时才编译,即对部分源程序行指定编译条件

一 条件存在

定义了某个宏,才能编译这些代码

[root@ansible9 ~]# cat test.c
#include <stdio.h>
#define AA
int main(int argc, char *argv[])
{
	# ifdef AA
		printf("宏AA定义了\n");
	# else
		printf("宏AA没定义了\n");
	# endif

	# ifdef BB
		printf("宏BB定义了\n");
	# else
		printf("宏BB没定义了\n");
	# endif
}
[root@ansible9 ~]# 
[root@ansible9 ~]# gcc -E test.c -o test.i

[root@ansible9 ~]# tail -15 test.i
# 3 "test.c"
int main(int argc, char *argv[])
{

  printf("宏AA定义了\n");







  printf("宏BB没定义了\n");

}
[root@ansible9 ~]# 

二 条件不存在

不定义某个宏,才编译这些代码

[root@ansible9 ~]# cat test.c
#include <stdio.h>
#define AA
int main(int argc, char *argv[])
{
	# ifndef AA
		printf("宏AA没定义了\n");
	# else
		printf("宏AA定义了\n");
	# endif

	# ifndef BB
		printf("宏BB没定义了\n");
	# else
		printf("宏BB定义了\n");
	# endif
}
[root@ansible9 ~]# gcc -E test.c -o test.i
[root@ansible9 ~]# tail -15 test.i
# 3 "test.c"
int main(int argc, char *argv[])
{



  printf("宏AA定义了\n");



  printf("宏BB没定义了\n");



}

三 条件判断是否成立

条件成立时才编译这些代码

[root@ansible9 ~]# cat test.c
#include <stdio.h>
#define AA
int main(int argc, char *argv[])
{
	int a = 3;
	int b = 5;
	# if a>b
		printf("a大于b\n");
	# else
		printf("a小于等于b\n");
	# endif
}
[root@ansible9 ~]# gcc -E test.c -o test.i
[root@ansible9 ~]# tail -15 test.i

# 2 "test.c" 2


# 3 "test.c"
int main(int argc, char *argv[])
{
 int a = 3;
 int b = 5;



  printf("a小于等于b\n");

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值