在使用STM8或STM32的過程中,在官方的庫文件中經常能看到assert_param()的使用,一直都是對它無視,因為它不影響使用。但作為一名合格的、嚴謹的工程師來講,連assert_param()斷言都沒搞明白,都沒弄清楚,自己感覺還是有點丟人的。
其實這個就是斷言,它的主要用途是在編程的過程中為程序員提供參數檢查,對于Release之后,對終端用戶而言是無用的。它是在開發調試過程中,對參數錯誤進行提示,以便程序員提高開發效率。
首先,在STM8L101F3P6官方提供的模版庫的main.c文件中我們會看到如下代碼:
void main(void)
{
/* Infinite loop */
while (1)
{
}
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval : None
*/
void assert_failed(uint8_t* file, uint32_t line)
{
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %drn", file, line) */
/* Infinite loop */
while (1)
{
}
}
#endif
其含義是:如果定義了USE_FULL_ASSERT宏,則程序包含了assert_failed()這個函數的定義。
在stm8l10x_conf.h文件中,我們也會看到如下的代碼:
/* Exported macro ------------------------------------------------------------*/
#ifdef USE_FULL_ASSERT
/**
* @brief The assert_param macro is used for function's parameters check.
* @param 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.
* @retval : None
*/
#define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__))
/* Exported functions ------------------------------------------------------- */
void assert_failed(uint8_t* file, uint32_t line);
#else
#define assert_param(expr) ((void)0)
#endif /* USE_FULL_ASSERT */
這里是assert_param()的原型。
可以看到,它是一個帶參數的宏定義,參數是一個條件表達式。表達式就是你要檢查的參數。
表達式為真時,其定義為(void)0。即空,什么都不做,對程序無影響。函數調用時傳來的參數都是正確的,不需要進行什么操作。
表達式為假時,其定義為assert_failed((uint8_t *)__FILE__,__LINE__)),這是一個帶兩個參數的函數,這個函數就是在main.c中定義的。第1個參數為文件指針,指示參數錯誤的文件;第2個參數是參數錯誤的等號。
--------------------------------------------------------------------------------------------------------------------------------------
1.使用時,要定義USE_FULL_ASSERT這個這宏,在stm8l10x_conf.h文件中去定義
2.可以是assert_failed()函數中,輸出一些提示性的信息,來方便自己調試。
--------------------------------------------------------------------------------------------------------------------------------------
上一篇:STVD中報can't open file crtsi0.sm8的問題
下一篇:讓STM8使用cosic編譯器時顯示ram flash stack占用信息
推薦閱讀
史海拾趣
設計資源 培訓 開發板 精華推薦
- 下載、評論贏雙重好禮|PI 邀您跟littleshrimp一起拆解小米最新二合一充電寶
- Keysight示波器主題月有獎系列活動之 注冊大獎天天抽 搶樓踩中亦有獎
- 限時秒殺,100本專業書籍——TI 中國大學計劃20周年
- ADI有獎下載活動之20:基于NDIR和PID的ADI氣體探測器解決方案和新產品
- 免費申請試用|福祿克Norma6000功率分析儀
- DigiKey應用探索站重磅上線!潮流應用,硬核技術探秘,N多干貨,一站get!
- 翻開《射頻技術For Dummies系列》書籍,跟帖漫談射頻世界
- 全新吉時利4200A SCS參數分析儀震撼上市,邀您參與翻蓋有禮!
- ADI基于ADPD188BI的煙霧探測器集成解決方案 有獎直播 5月13日上午10:00-11:30 為您揭曉!
- 最后一周報名,STM32中國峰會暨粉絲狂歡節,5月12-13日深圳