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 MYDEBUGprintf("test\n"); #endifprintf("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的含義了吧。不信,就親自動手試試吧。
總結
以上是生活随笔為你收集整理的gcc -D选项的作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一个简单的WebService服务
- 下一篇: 解决添加打印机print spooler