1. 程式人生 > >GCC編譯時增加巨集定義-D識別符號,相當於巨集定義#define 識別符號

GCC編譯時增加巨集定義-D識別符號,相當於巨集定義#define 識別符號

GCC編譯時增加巨集定義-D<識別符號>,相當於#define <識別符號>,可以在遇到條件編譯時執行。

#ifdef <識別符號>
    //條件編譯內容
#endif

例子: 搭配gcc編譯命令:gcc -DDEBUG -g -o main.out main.c (注意-D<識別符號>應該緊跟gcc後面,-o等指令前面)
main.c

#include <stdio.h>
//如果在gcc編譯引數中定義了-DDEBUG,就相當於在程式碼中定義#define DEBUG
//#define DEBUG 
int main(int argc,
char *argv[]) { #ifdef DEBUG printf("define DEBUG\n"); #else printf("no define DEBUG\n"); #endif printf("hello world\n"); return 0; }

其實不管是將DEBUG定義為什麼,常量、函式等,只要定義過DEBUG,都可以在條件編譯時執行
例如:#define DEBUG 0 or #define DEBUG 1 or #define DEBUG(x) x+1 等等,在#ifdef DEBUG判斷時都可以通過。