Makefile如何通过宏开关进行条件编译

  在开发中经常会遇到需要条件编译一段代码,即:

  #ifdef DEBUG

  { 如果定义了DUBUG,则执行此段代码!}

  #else

  {否则执行此段代码!}

  这就需要通过宏开关来进行条件编译,也就是常说的编译开关。

  下面给出详细的代码实现。

  //hello.c

 1 #include<stdio.h>
 2 void main()
 3 {
 4 #ifdef DEBUG
 5 printf("#ifdef DEBUG is running!
");
 6 #else 
 7 printf("#else is running!
");
 8 #endif
 9 return ;
10 }

  //Makefile

1 ifeq ($(debug),yes)
2 CFLAGS:= -DDEBUG 
3 endif
4 hello:hello.c
5     gcc $(CFLAGS) $< -o $@

  测试结果:

1 $ make
2 gcc hello.c -o hello
3 $ ./hello
4 #else is running!
5 $rm hello
6 $ make debug:=yes
7 gcc -DEBUG hello.c -o hello
8 $ ./hello
9 #ifdef DEBUG is running!
原文地址:https://www.cnblogs.com/sj-lv/p/3456713.html