c++ #ifdef的用法


http://www.tuicool.com/articles/mIJnumB

 

#ifdef的用法

   靈活使用#ifdef指示符,我們可以區隔一些與特定頭文件、程序庫和其他文件版本有關的代碼。
代碼舉例:新建define.cpp文件

[cpp]  view plain copy
 
  1. #include "iostream.h"  
  2. int main()  
  3. {  
  4. #ifdef DEBUG   
  5. cout<< "Beginning execution of main()";  
  6. #endif   
  7. return 0;  
  8. }  
運行結果為:Press any key to continue

改寫代碼如下:
[cpp]  view plain copy
 
  1. #include "iostream.h"  
  2. #define DEBUG  
  3. int main()  
  4. {  
  5. #ifdef DEBUG   
  6. cout<< "Beginning execution of main()";  
  7. #endif   
  8. return 0;  
  9. }  
運行結果為:Beginning execution of main()
Press any key to continue

更一般的情況是,#define語句是包含在一個特定的頭文件中。
比如,新建頭文件head.h,在文件中加入代碼:

[cpp]  view plain copy
 
  1. #ifndef DEBUG  
  2. #define DEBUG  
  3. #endif  
  4.   
  5. 而在define.cpp源文件中,代碼修改如下:  
  6. #include "iostream.h"  
  7. #include "head.h"  
  8. int main(){  
  9. #ifdef DEBUG   
  10. cout<< "Beginning execution of main()";  
  11. #endif   
  12. return 0;  
  13. }  

運行結果如下: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

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM