比如有下面这个程序(helloworld.c):
> #include <stdio.h>
> int main(){
> #ifdef A
> printf("hello world !");
> #endif
> return 0;
> }
这个程序当A被define后,会输出"hello world !",否则do nothing.
Makefile如下:
> helloworld:
> gcc helloworld.c -o helloworld
用上面的Makefile编译生成的程序执行不会产生任何输出。要使程序输出"hello world !",除了在程序文件中 "#define A"之外,还有其他方法:
在Makefile中增加 -DA 选项,即:
>helloworld:
> gcc -DA hellowrold.c -o helloworld
或者定义一个(需要时当然可以是多个)变量,如:
>EXTRA_FLAG := -DA
>helloworld:
> gcc $(EXTRA_FLAG) helloworld.c -o helloworld
> #include <stdio.h>
> int main(){
> #ifdef A
> printf("hello world !");
> #endif
> return 0;
> }
这个程序当A被define后,会输出"hello world !",否则do nothing.
Makefile如下:
> helloworld:
> gcc helloworld.c -o helloworld
用上面的Makefile编译生成的程序执行不会产生任何输出。要使程序输出"hello world !",除了在程序文件中 "#define A"之外,还有其他方法:
在Makefile中增加 -DA 选项,即:
>helloworld:
> gcc -DA hellowrold.c -o helloworld
或者定义一个(需要时当然可以是多个)变量,如:
>EXTRA_FLAG := -DA
>helloworld:
> gcc $(EXTRA_FLAG) helloworld.c -o helloworld
本文介绍了一个简单的C语言程序如何通过预处理指令控制代码的行为,并展示了如何利用Makefile中的编译选项来达到同样的效果。这为理解编译过程及代码条件编译提供了一个实用的例子。

2797

被折叠的 条评论
为什么被折叠?



