
條件編譯 (conditional compilation) 用來判斷常數運算式的結果,例如某個識別字名稱是否存在,如果不存在就用 #define 定義。條件編譯有以下的指令
| 指令語法 | 功能 |
|---|---|
| #if expr | 判斷 expr 是否為真。 |
| #ifdef expr | 判斷 expr 是否有定義。 |
| #ifndef expr | 判斷 expr 是否沒有定義。 |
| #elif expr | 當上述指令結果為假時的另一個條件。 |
| #else | 當上述指令皆假時所執行的部份。 |
| #endif | 結束條件編譯。 |
舉例如下
| 001 | #include <iostream> |
| 002 | |
| 003 | int main() { |
| 004 | #if -1 > 0 |
| 005 | std::cout << "mm" |
| 006 | << std::endl; |
| 007 | #elif 1 > 0 |
| 008 | std::cout << "ok" |
| 009 | << std::endl; |
| 010 | #else |
| 011 | std::cout << "xx" |
| 012 | << std::endl; |
| 013 | #endif |
| 014 | |
| 015 | return 0; |
| 016 | } |
| 017 | |
| 018 | /* Kaiching Chang |
| 019 | u1401_1.cpp |
| 020 | 2014-02 */ |
這裡用了 #if 、 #elif 、 #else 與 #endif ,用法類似 if-else 陳述
| 004 | #if -1 > 0 |
| 005 | std::cout << "mm" |
| 006 | << std::endl; |
| 007 | #elif 1 > 0 |
| 008 | std::cout << "ok" |
| 009 | << std::endl; |
| 010 | #else |
| 011 | std::cout << "xx" |
| 012 | << std::endl; |
| 013 | #endif |
編譯執行,結果如下
| $ g++ u1401_1.cpp |
| $ ./a.out |
| ok |
| $ |
前置處理器指令結尾都不需要加上分號。
另舉一例使用 #if
| 001 | #include <iostream> |
| 002 | #define DEMO1 10 |
| 003 | |
| 004 | int main() { |
| 005 | #ifdef DEMO1 |
| 006 | std::cout << "demo1" |
| 007 | << std::endl; |
| 008 | #else |
| 009 | std::cout << "no demo1" |
| 010 | << std::endl; |
| 011 | #endif |
| 012 | |
| 013 | #ifndef DEMO2 |
| 014 | std::cout << "no demo2" |
| 015 | << std::endl; |
| 016 | #else |
| 017 | std::cout << "demo2" |
| 018 | << std::endl; |
| 019 | #endif |
| 020 | |
| 021 | return 0; |
| 022 | } |
| 023 | |
| 024 | /* Kaiching Chang |
| 025 | u1401_2.cpp |
| 026 | 2014-02 */ |
此例先定義一個巨集常數 DEMO1
| 002 | #define DEMO1 10 |
然後判斷 DEMO1 及 DEMO2 是否存在。編譯執行,結果如下
| $ g++ u1401_2.cpp |
| $ ./a.out |
| demo1 |
| no demo2 |
| $ |
一個常見的應用是在標頭檔中判斷是否已經引入,例如
| #ifndef DATA_H | |
| #define DATA_H | |
| // data.h | |
| #endif DATA_H |
continue ...
沒有留言:
張貼留言