'Function-like macro, 'REPORT_ERROR', defined [MISRA 2012 Directive 4.9, advisory]
I have defined the MACRO
, which will call the function and pass the argument. Getting below MISRA warning for this case. Is it not allowed? How to avoid this?
What are the advantages of calling a function(s) in MACRO
as below?
#define REPORT_ERROR(Id, Error) ReportErr((uint16)21, (uint8)0, (uint8)Id, (uint8)Error)
void ReportErr(uint16 ModuleId, uint8 InstanceId, uint8 ApiId, uint8 ErrorId)
{
// function - body
}
Solution 1:[1]
Some of the MISRA-C rules are "very advisory", to the point where you can't possibly conform to them and might want to raise a permanent deviation against them. One perfect example of this is the rule against using function-like macros.
Every C programmer knows that function-like macros are bad, for many sound reasons. But often there's just no way around them. So the importance of the rule is to give a nudge that function-like macros should be the last resort, in case the programmer somehow managed to be unaware of this. There's no practical use for the rule.
In this specific case, it seems that the macro is only there to compensate for bad API or bad caller code. There are many alternative ways you could solve this:
- Make some function parameters optional, by allowing the caller to pass NULL or similar.
- Use some sort of default argument set on the caller-side and pick arguments there depending on use-case.
- If neither of the above is an option, use a separate function, or an inline wrapper function.
Other things:
MISRA or no MISRA, you should not have "magic numbers" anywhere in your code. There shouldn't be a magic number 21
out of the blue, this needs to be replaced with a named constant.
Also, you should use stdint.h
instead of using your own garage standard for integer types. If stuck with C90, then use typedefs in a custom header corresponding to those in stdint.h
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |