2

I'm trying to utilize misra C:2012 checking in from cppcheck (v2.9). However, when executing on a particular file I get the following violations:

vehicle_controller.c:1494:2: style: All identifiers used in the controlling expression of #if or #elif preprocessing directives shall be #define’d before evaluation. [misra-c2012-20.9] #if OS == LINUX_OS ^ src/emb/bwk/

I'm using the following command to execute:

$ cppcheck -DOS=LINUX_OS --addon=misra.json vehicle_controller.c

Is there a different way to pass #define to be properly picked up by the misra checking?

Lundin
  • 195,001
  • 40
  • 254
  • 396
ls6777
  • 386
  • 1
  • 5
  • 14

1 Answers1

3

As per the examples within Rule 20.9, an undefined identifier results in a zero value:

#if OS == 0    /* Non-compliant - OS may be zero or undefined */
...
#endif

The MISRA compliant approach is to ensure that the identifier is defined before use. Thus:

#ifndef OS
...                   /* OS is undefined           */
#else
  #if OS == 0
  ...                 /* OS is defined as zero     */
  #else
  ...                 /* OS is defined as non-zero */
  #endif
#endif
Lundin
  • 195,001
  • 40
  • 254
  • 396
Andrew
  • 2,046
  • 1
  • 24
  • 37
  • I understand what the issue is. I'm asking how to pass the `#define` on the command line or in some type of configuration file. I DO have `OS` defined before use. It's part of our build configuration. I'm trying to simulate that somehow on the command line or a config file used by cppcheck and/or misra.py – ls6777 Jan 09 '23 at 16:31
  • 1
    ``cppcheck -DOS=LINIX`` should work fine. Are you sure that it is not defined? R.20.9 requires that you do check (as per my answer) and not assume. – Andrew Jan 10 '23 at 09:15
  • 1
    Alternatively, `#if defined(OS) && (OS == something)` to ensure that each line is safe in itself, or to reduce the number of nested `#ifdef/#ifndef/#if`. Or yet another alternative: `#ifndef OS ... #elif OS == 0 ... #else ... #endif`. – Lundin Jan 10 '23 at 09:47
  • @Andrew It's strange that when I use polyspace for misra checking, it doesn't flag this as an issue. I assumed because `OS` is defined as part of polyspace configuration. If this method of syntax is required to make cppcheck happy for misra checking, then I probably can't use it. That would require massive code refactoring unfortunately. – ls6777 Jan 10 '23 at 16:19
  • 1
    Given my affiliation, I won't comment on tools. As the rule is *required* you can, of course, deviate with justification. – Andrew Jan 10 '23 at 17:16
  • 1
    @Andrew Thanks for all the info! Definitely helps to understand it more and understand intent of Rules! – ls6777 Jan 10 '23 at 17:34