2013-04-07 90 views
0

請看看下面的代碼編譯只有一個的if-else

#include <iostream> 
using namespace std; 

    int main(){ 
     #if true 
      int fd = 0; 

     #else 
      int dd =0; 
     #endif 
     cout<<fd; 
     //cout<<dd; 

     system("pause"); 
     return 0; 
    } 

部分。在這裏,我試圖編譯只有一個街區。如果'如果'編譯,那麼'其他'不應該像智慧一樣。但是這不起作用。請幫忙。

+2

它不起作用? LWS測試運行良好。 – chris 2013-04-07 06:18:14

+1

適用於我的機器(gcc版本4.2.1(基於Apple Inc. build 5658)(LLVM build 2336.11.00))。你使用什麼編譯器? – 2013-04-07 06:22:21

+0

什麼是不工作,以及如何?請描述你的預期和實際結果。 – 2013-04-07 06:35:42

回答

3

對於條件編譯代碼必須是這個樣子:

#include <iostream> 
using namespace std; 

int main(){ 
    #ifdef Somedef 
     int fd = 0; 
     cout<<fd; 
    #else 
     int dd =0; 
     cout<<dd; 
    #endif 
    system("pause"); 
    return 0; 
} 

然後在編譯的代碼給出的定義如命令行參數:GCC -DSomedef test.c的-o測試,包括代碼並刪除命令行定義以刪除代碼

注意:您已經選中「#if true」作爲條件編譯,該語句將始終爲true,因此將在編譯時包含該部分代碼。