简单点说,加上-D选项就是在编译时增加对-D后面的宏的定义。来看个简单的例子吧,源程序(a.c)如下:
- #include <stdio.h>
- int main(int argc, char *argv[])
- {
- #ifdef MYDEBUG
- printf("test\n");
- #endif
- printf("hello world\n");
- return 0;
- }
编译及输出如下:
[root@test #9]#gcc -DMYDEBUG -g -o a1 a.c @1
[root@test #11]#./a1
test
hello world
[root@test #12]#gcc -DDEBUG -g -o a2 a.c @2
[root@test #13]#./a2
hello world
[root@test #14]#gcc -g -o a3 a.c @3
[root@test #15]#./a3
hello world
可见,第2和第3条编译指令的输出结果是一样的,为什么呢?
先看@1,因为源程序中有条件判断,是否定义了宏“MYDEBUG”,而该编译指令中刚好带了"MYDEBUG",所以就输出了“test";
接着看@2, 编译指令中-D后是”DEBUG“,这个针对”#ifdef MYDEBUG"而言就是false,所以就不会输出“test";
最后看@3, 编译指令中无-D选项,所以也不会输出”test"。
这样做比较,相信大家都明白这个-D的含义了吧。不信,就亲自动手试试吧。