2

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?

Community
  • 1
  • 1
Salahuddin
  • 1,617
  • 3
  • 23
  • 37
  • 1
    `even if it is not a reserved macro?` it *could* be used in an other implementation, or even in an other version of this implementation. – joop Jun 05 '18 at 09:46
  • OK. So how can I solve it? It's hard to change '__I' in all of the library modules! – Salahuddin Jun 05 '18 at 09:54
  • 2
    User code should not use leading underscores; thay are reserved for the implementation and the libraries. So you should only change *your own* code, removing all leading underscores.from `#define _xyz ...` And dont change the librariy headers. These are made by people who are supposed to know what they are doing. 9You could, of course *refer* to macros in the library headers, but never (re) *define* them) – joop Jun 05 '18 at 09:58
  • 3
    The underscore naming is a C standard requirement, not a MISRA requirement. – Lundin Jun 05 '18 at 10:41
  • For whatever reason a compiler may predefine `__MY_HEADER_`. So, the group that is controlled by `#ifndef __MY_HEADER_` is skipped. – pmor May 11 '22 at 16:19

1 Answers1

6

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

Alexander Dmitriev
  • 2,483
  • 1
  • 15
  • 20