gcc -D选项的作用

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的含义了吧。不信,就亲自动手试试吧。



  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值