Search code examples
clintmisra

MISRA C 2012 - Rule 21.1 - Macros starting with underscore


Rule 21.1 in MISRA C 2012 states that

#define and #undef shall not be used on a reserved identifier or reserved macro name

This rule applies to identifier or macro beginning with an underscore

Rationale:

Removing or changing the meaning of a reserved macro may result in undefined bahaviour

I don't understand why macro's name shall not start with an unerscore, even if it is not a reserved macro? For example in my header files:

#ifndef __MY_HEADER_
#define __MY_HEADER_

or in a library I'm using:

#define __I volatile const

Should I change all my code and the library I'm using (which is a big library) in order to conform to this rule or is there a simpler solution?


Solution

  • According to C standard (section 7.1.3), all identifiers starting with _[A_Z] or __ are reserved. As they are reserved, common sense and rule 21 forbid you to modify (redefine or undefine) them (or create your own).

    Thus, you should change your code to not using leading underscores even in include guards not to mention your macros.

    Some further reading can be found e.g. here: Include guard conventions in C