您的位置:首页 > 编程语言

用gcc 的-D 参数来调试代码

2011-04-18 10:19 169 查看
写代码免不了要加入调试信息,在程序头定义一个DEUBG开关很烦,不过gcc早就想到了,有-D选项。

man gcc

或者

man gcc | col -b > gcc.txt

相关信息如下:

GCC(1) GNU GCC(1)

NAME

gcc - GNU project C and C++ compiler

SYNOPSIS

gcc [-c|-S|-E] [-std=standard]

[-g] [-pg] [-Olevel]

[-Wwarn...] [-pedantic]

[-Idir...] [-Ldir...]

[-Dmacro[=defn]...] [-Umacro]

[-foption...] [-mmachine-option...]

[-o outfile] infile...

Only the most useful options are listed here; see below for the

remainder. g++ accepts mostly the same options as gcc.

-----------------------

Preprocessor Options

-Aquestion=answer -A-question[=answer] -C -dD -dI -dM -dN

-Dmacro[=defn] -E -H -idirafter dir -include file -imacros file

-iprefix file -iwithprefix dir -iwithprefixbefore dir -isystem

dir -M -MM -MF -MG -MP -MQ -MT -nostdinc -P -fwork-

ing-directory -remap -trigraphs -undef -Umacro -Wp,option

-Xpreprocessor option

----------------------

-D name

Predefine name as a macro, with definition 1.

-D name=definition

Predefine name as a macro, with definition definition. The con-

tents 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 new-

line 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.

-U name

Cancel any previous definition of name, either built in or pro-

vided with a -D option.

-----------------------------------

-D 定义宏(D-define)

-D定义宏有两种情况,一种是-DMACRO 相当于程序中使用#define MACRO 另外可以-DMACRO=A 相当于程序中使用#define MACRO A 这只是一个编绎参数,在连接时没有意义

如: $gcc -c hello.c -o hello.o -DDEBUG

上面为hello.c定义了一个DEBUG宏,某些情况下使用-D 代替直接在文件中使用#define,也是为了避免修改源代码双。例如一个程序希望在开发调试的时候能打印出调试信息,而正式发布的时候就不用打印了,而且发布前不用修改源代码双。可以这样

#ifdefine DEBUG

printf("debug message/n");

#endif

对于这段代码,平时调试的时候就加上-DDEBUG 发布时不用-D选项

与之对应的是-UMACRO参数,相当于#undef MACRO,取消宏定义

============hello.c======

#include <stdio.h>

#include <stdlib.h>

int main()

{

#ifdef DEBUG

printf("this is before/n");

#endif

printf("helloworld/n");

#ifdef DEBUG

printf("this is end/n");

#endif

exit(0);

}

$gcc -c hello.c -o hello.o -DDEBUG -Wall

则./hello输出:

this is before

helloworld

this is end

$gcc -c hello.c -o hello.o -Wall

则./hello输出:

helloworld

方便!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: