Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

搞懂 gcc 的 -D 與 -U:原來那一長串參數就是宏

第一次看到這樣一串編譯參數,多半會頭皮發麻:

CCFLAGS=" -w -enable-threads=posix -DLINUX -D_REENTRANT -DWORKONGN -Dlinux -D_GN_DETAIL_SDR_"

折騰半天才發現:那些 -D 其實就是「定義巨集」而已。

-D:在命令列定義巨集

看個最經典的例子:

/* hello.c */
#include <stdio.h>

#ifdef YES
char* str = "Yes, this is a macro.";
#else
char* str = "No, there is no macro.";
#endif

int main()
{
    printf("%s\n", str);
    return 0;
}

帶上 -DYES 編譯:

recordus@LFS test # gcc -DYES -o helloyes hello.c
recordus@LFS test # ./helloyes
Yes, this is a macro.

不帶:

recordus@LFS test # gcc -o hellono hello.c
recordus@LFS test # ./hellono
No, there is no macro.

-U:取消已定義的巨集

與 -D 相對的 -U 用來「取消」巨集,因此兩個一起用會互相抵銷:

root@LFS test # gcc -DYES -UYES -o helloyesno hello.c
root@LFS test # ./helloyesno
No, there is no macro.

所以回頭看那串 -DLINUX -D_REENTRANT -Dlinux,不過是告訴編譯器:這份程式碼要按 Linux、可重入(reentrant)的條件來預處理,讓原始碼裡的 #ifdef 走到正確分支。理解這點之後,看到再長的參數串也不會慌了。

Copyright © Linux教程網 All Rights Reserved