Misra rule 19.7 : function like macro

佐手、 提交于 2019-12-20 04:13:21

问题


I have a warning regarding Misra rule 19.7 : A function should be used in preference to a function-like macro in the below line :

#define gOFFSETOF(type, mem) (gOFFSET)((size_t) ((char *)&((type *) 0)->mem - (char *)((type *) 0)))

how should I solve this ?


回答1:


Rule 19.7 (advisory): A function should be used in preference to a function-like macro. While macros can provide a speed advantage over functions, functions provide a safer and more robust mechanism. This is particularly true with respect to the type checking of parameters, and the problem of function-like macros potentially evaluating parameters multiple times.

The rule is advisory, so this means it "should normally be followed":

Note that the status of "advisory" does not mean that these items can be ignored, but that they should be followed as far as is reasonably practical. Formal deviations are not necessary for advisory rules, but may be raised if it is considered appropriate.

So you have the option to break the rule without making a formal deviation.

Now, in answer to your question, "how should I solve this?", you have two choices given that this macro function can't be implemented as a function.

Option 1: deviate from rule 19.7

The advisory makes it clear that functions are nicer than macro functions, and cites the section in C Traps and Pitfalls, Andrew Koenig (1988) on comparing macro functions with functions, but describes it as a preference, and specifically over the short macro functions designed for "speed advantage".

If you believe this macro makes the code clearer, conciser, and you have suitably avoided the common pitfalls of macro functions, then you can deviate from rule 19.7 without making a formal specific deviation, and without failing compliance.

Option 2: remove the macro function

If after considering the advisory you deem it appropriate then remove the macro function. You may want to write more functions to break up the extra inline code, and/or avoid needless code duplication.




回答2:


Rule 19.7 is advisory so you are free to ignore it, if you only document doing so in your compliance matrix. However, this is a very good rule and that macro is very unsafe. You should not write code like that in mission-critical software.

The best solution is indeed to do as MISRA says, avoid function-like macros, but instead write a real function. That way you get strong typing and safe code.



来源:https://stackoverflow.com/questions/18444813/misra-rule-19-7-function-like-macro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!