gcc -D选项在man中的说明如下:
-D name
Predefine name as a macro, with definition 1.
-D name=definition
The contents of definition are tokenized and processed as if they
appeared during translation phase three in a #define directive. In
particular, the definition will be truncated by embedded newline
characters.
If you are invoking the preprocessor from a shell or shell-like
program you may need to use the shell’s quoting syntax to protect
characters such as spaces that have a meaning in the shell syntax.
If you wish to define a function-like macro on the command line,
write its argument list with surrounding parentheses before the
equals sign (if any). Parentheses are meaningful to most shells,
so you will need to quote the option. With sh and csh,
-D’name(args...)=definition’ works.
-D and -U options are processed in the order they are given on the
command line. All -imacros file and -include file options are
processed after all -D and -U options.
简单点说,加上-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的含义了吧。不信,就亲自动手试试吧。