#if, #ifdef, #ifndef, #else, #elif, #endif的用法
#ifdef的用法
?? 靈活使用#ifdef指示符,我們可以區隔一些與特定頭文件、程序庫和其他文件版本有關的代碼。
代碼舉例:新建define.cpp文件
改寫代碼如下:
Press any key to continue
更一般的情況是,#define語句是包含在一個特定的頭文件中。
比如,新建頭文件head.h,在文件中加入代碼:
運行結果如下:Beginning execution of main()
Press any key to continue
結論:通過使用#ifdef指示符,我們可以區隔一些與特定頭文件、程序庫和其他文件版本有關的代碼
?
#if, #ifdef, #ifndef, #else, #elif, #endif的用法:
? 這些命令可以讓編譯器進行簡單的邏輯控制,當一個文件被編譯時,你可以用這些命令去決定某些代碼的去留,
這些命令式條件編譯的命令。
常見的條件編譯的三種形式:
①第一種形式:??
#if?defined(或者是ifdef)<標識符(條件)>?
<程序段1>
#endif??
②第二種形式:??
#if?!defined(或者是ifndef)<標識符(條件)>?
<程序段1>?
? #ifdef?…?
[#elif?…?]?
[#elif?…]?
#else?…??
#endif
示例:
#include <iostream>
using namespace std;
int main()?
{?
#if DEBUG ?/*或者是#ifdef DEBUG*/?
cout << "條件成立,DEBUG已經定義了!" <<endl;?
#else?
cout << "條件不成立,DEBUG還沒定義" <<endl;?
#endif?
return 0;?
}
//結果輸出:?條件不成立,DEBUG還沒定義
//如果是添加了#define DEBUG ,輸出結果是:條件成立,DEBUG已經定義了!
#include <iostream>?
using namespace std;?
#define DEBUG?
int main()?
{?
#ifdef DEBUG /*或者是#ifdef DEBUG*/?
cout << "條件成立,DEBUG已經定義了!" <<endl;?
#else?
cout << "條件不成立,DEBUG還沒定義" <<endl;?
#endif?
return 0;?
}
//要注意的是,如果是#define 宏名,沒有宏體如 #define DEBUG,就必須使用#ifdef或#ifndef與之對應,
//如果是#define 宏名 宏體,如 #define NUM 1,#if 和#ifdef都可以使用。
/*
#define的用法:
*/
示例二:
#include <iostream>?
using namespace std;?
#define NUM? 10?
int main()?
{?
??????? #ifndef NUM?
??????? cout << "NUM沒有定義!"<<endl;?
??????? #elif NUM >= 100?
??????? cout << "NUM >100" <<endl;?
??????? #elif NUM <100 && NUM >10?
??????? cout << "10 < NUM < 100" <<endl;?
??????? #elif NUM == 10?
??????? cout << "NUM ==10" <<endl;?
??????? #else?
??????? cout << "NUM < 10" << endl;?
??????? #endif?
??????? return 0;?
}?
//輸出NUM ==10?
?
?
?
也可以在mk文件定義NUM
ifeq ($(BOARD_SCREENRECORD_LANDSCAPE_ONLY),true)
LOCAL_CFLAGS += -DNUM
endif
總結
以上是生活随笔為你收集整理的#if, #ifdef, #ifndef, #else, #elif, #endif的用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: “年少当攀第一流,恰如明月冠中秋”
- 下一篇: 理解C++中拷贝构造函数