2010-02-08 51 views

回答

50

任何地方:

#ifndef DEBUG 
#error Only Debug builds are supported 
#endif 
3

如果您只是想報告錯誤:

#ifdef RELEASE 
    #error Release mode not allowed 
#endif 

將與大多數編譯器的工作。

4

您可以使用error指令。下面的代碼在編譯時將拋出一個錯誤,如果沒有定義DEBUG

#ifndef DEBUG 
#error This is an error message 
#endif 
+0

對不起,我混合編譯和錯誤,而打字。更正了答案。 – 2010-02-08 23:32:31

13

C提供了一個#error語句,大多數編譯器添加#warning聲明。 The gcc documentation recommends引用該消息。

+1

@Antonio對,沒有[更多]推薦。我用一個替換爲gcc doc的鏈接。 – philant 2015-11-17 17:29:57

6

也許東西更復雜,但它只是複製&以前的解決方案的粘貼。 :-)

#ifdef DEBUG   
    #pragma message ("Debug configuration - OK") 
#elif RELEASE 
    #error "Release configuration - WRONG" 
#else 
    #error "Unknown configuration - DEFINITELY WRONG" 
#endif 

P.S.如何生成警告也有一種方法。 創建未引用的標籤,如

HereIsMyWarning: 

並且不引用它。在編譯過程中你會得到警告像

1>..\Example.c(71) : warning C4102: 'HereIsMyWarning' : unreferenced label 
1

GCC和Clang的(也可能是任何編譯器支持_Pragma功能),你可以定義一個宏:

#if ! DEBUG 
#define FIX_FOR_RELEASE(statement) _Pragma ("GCC error \"Must be fixed for release version\"") 
#else 
#define FIX_FOR_RELEASE(statement) statement 
#endif 

您可以使用此宏暫時的黑客,例如繞過同事尚未編寫的代碼,以確保在您想向公衆發佈構建版本時不會忘記修復它。無論是

FIX_FOR_RELEASE() 
// Code that must be removed or fixed before you can release 

FIX_FOR_RELEASE(statement that must be removed or fixed before you can release); 
1

代碼::塊,如果你不想要的釋放模式,你可以刪除釋放模式。爲此,請單擊「項目」菜單,選擇「屬性...」,然後在「構建目標」選項卡中單擊「發佈」,然後單擊「刪除」按鈕。只有刪除發行模式才能用於當前項目,因此您仍然可以在其他項目中使用它。

否則,如果你真的想使用預處理,你可以這樣做:

#ifdef RELEASE 
#error "You have to use the Debug mode" 
#endif