2024-09-19 11:44 PM - last edited on 2024-09-21 01:32 AM by Andrew Neil
Hi everyone,
I’ve noticed that STM32 drivers make extensive use of macros, and I’m curious about the reasoning behind this. Is the primary motivation is to increase performance / improve maintainability / are there other factors involved?
2024-09-23 07:27 AM - edited 2024-09-23 07:29 AM
@TDK wrote:If you replaced the macro with a function, why would the function be empty?
We're talking about mimicking the case of a "null" macro - expanding to nothing at all:
#ifdef USE_FULL_ASSERT
/**
void assert_param(expr)
{
((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__));
}
#else
void assert_param(expr)
{
}
#endif /* USE_FULL_ASSERT */
2024-09-23 07:29 AM - edited 2024-09-23 07:48 AM
Gems of the C preprocessor wisdom are scattered here and there in blogs and articles...
" removing the preprocessor is treated as a moral issue, but it's also the reason your language design will never replace C, and as a moralizing language designer, you need to know that and make a conscious decision about it. Yes, the C preprocessor is used for all sorts of egregious hacks. I have bad news for you: that's what it's made for."
Some time ago I stumbled upon this book, 21st Century C. Intriguing title, but the content was disappointing. Would like to see a new edition that covers modern best practices, tooling, clang, emerging C23/24 standard, CMake... But who writes such books these days.
2024-09-23 08:48 AM - edited 2024-09-23 08:50 AM
One problem with this scheme is that __FILE__ and __LINE__ no longer correspond to where the error happened, but instead to where the assert_param function was defined--not very useful. I would suspect that was one of the reasons for using a macro in the first place.
2024-09-25 08:10 AM
@TDK wrote:MISRA doesn't flat out forbid macros, or function-like macros.
It also doesn't expect third-party code to be MISRA compliant - the MISRA Compliance document calls this "Adopted Code", and it's use may be sufficient to justify the non-compliance (though measures must be taken to ensure that any third-party code is of an appropriate quality, supported by documentation, and it is better if it is MISRA compliant).
Note that there is a secondary issue as compliance is not absolute and depends on the tools and processes used to check for compliance (due to decidability issues, the locations in the code against which non-compliances are reported, ...).
I generally create an "Application" folder for the source code that I provide and only consider this as being in scope for MISRA compliance, with the "Core" and "Drivers" folders being tagged as third-party / out-of-scope (though any headers included within the application code are in scope). The MISRA guidelines that are tagged as requiring system analysis need to be checked across all of the application, core and driver code as there may be an undesirable interaction that only show at link time).