這段文字借鑒了Hans.Cai的原文(https://www.cnblogs.com/caihongsheng/p/3514523.html):
程序一般分為Debug 版本和Release 版本,Debug 版本用於內部調試,Release 版本發行給用戶使用。
assert(斷言)的作用:
①首先,斷言assert 是僅在Debug 版本起作用的宏,
②用於檢查“不應該”發生的情況。在運行過程中,如果assert 的參數為假,那么程序就會中止(一般還會出現提示對話,說明在什么地方引發了assert)。
用法說明:
在STM32的固件庫和提供的例程中,到處都可以見到assert_param()的使用。如果打開任何一個例程中的stm32f10x_conf.h文件,就可以看到實際上assert_param是一個宏定義;在固件庫中,它的作用就是檢測傳遞給函數的參數是否是有效的參數。
所謂有效的參數是指滿足規定范圍的參數,比如某個參數的取值范圍只能是小於3的正整數,如果給出的參數大於3,則這個assert_param()可以在運行的程序調用到這個函數時報告錯誤,使程序員可以及時發現錯誤,而不必等到程序運行結果的錯誤而大費周折。
這是一種常見的軟件技術,可以在調試階段幫助程序員快速地排除那些明顯的錯誤。它確實在程序的運行上犧牲了效率(但只是在調試階段),但在項目的開發上卻幫助你提高了效率。
當你的項目開發成功,使用release模式編譯之后,或在stm32f10x_conf.h文件中注釋掉對USE_FULL_ASSERT的宏定義,所有的assert_param()檢驗都消失了,不會影響最終程序的運行效率。
在執行assert_param()的檢驗時,如果發現參數出錯,它會調用函數assert_failed()向程序員報告錯誤,在任何一個例程中的main.c中都有這個函數的模板,如下:
1 #ifdef USE_FULL_ASSERT 2 /** 3 * @brief Reports the name of the source file and the source line number 4 * where the assert_param error has occurred. 5 * @param file: pointer to the source file name 6 * @param line: assert_param error line source number 7 * @retval None 8 */ 9 void assert_failed(uint8_t *file, uint32_t line) 10 { 11 /* USER CODE BEGIN */ 12 /* User can add his own implementation to report the file name and line number, 13 tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ 14 /* USER CODE END */ 15 } 16 #endif /* USE_FULL_ASSERT */
用戶可以按照自己使用的環境需求,添加語句輸出錯誤的信息提示,或修改這個函數做出錯誤處理。