三种条件编译
一般情况下源程序中所有行都参加编译,但有时需要对部分源程序行只在满足一定条件时才编译,即对部分源程序行指定编译条件
一 条件存在
定义了某个宏,才能编译这些代码
[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");
}