在除錯程式時,經常會用到assert和printf之類的函式,我最近做的這個工程裡就有幾百個assert,在你自認為程式已經沒有bug的時候,就要除去這些除錯程式碼,應為系統在正常執行時這些用於除錯的資訊是無用的,而且會佔用時間和空間。怎麼刪除呢,以下僅供參考!
下面給出最簡單的一種方法:
#define DEBUG
#ifdef DEBUG
#define PRINTF(x) printf x
#else
#define PRINTF(x) ((void)0)
#endif
使用時,PRINTF(( "Hello World!" ));
注意這裡是兩個括號,一個會報錯的'
不使用時,直接將"#define DEBUG"遮蔽掉
另外一個除錯時常用的方法是assert,還是在一個頭檔案裡,這裡用的是STM32函式庫的例子
#ifdef DEBUG 1
/************************************************************
* Macro Name : assert_param
* Description : The assert_param macro is used for function's parameters check.
* It is used only if the library is compiled in DEBUG mode.
* Input : - expr: If expr is false, it calls assert_failed function
* which reports the name of the source file and the source
* line number of the call that failed.
* If expr is true, it returns no value.
* Return : None
************************************************************/
#define assert_param(expr) ((expr) ? (void)0 : assert_failed((u8 *)__FILE__, __LINE__))
/* Exported functions -------------------------------------*/
void assert_failed(u8* file, u32 line);
#else
#define assert_param(expr) ((void)0)
#endif/* DEBUG */
//assert_failed此函式要自己定義
#ifdef DEBUG
/************************************************************
* Function Name : assert_failed
* Description : Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* Input : - file: pointer to the source file name
* - line: assert_param error line source number
* Output : None
* Return : None
************************************************************/
void assert_failed(u8* file, u32 line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d", file, line) */
/* Infinite loop */
while (1){
}
}
#endif