MISRA Discussion Forums
Rule 3-1-1 and constant declarations - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: MISRA C++:2008 rules (https://forum.misra.org.uk/forumdisplay.php?fid=19)
+---- Forum: 6.3 Basic concepts (C++) (https://forum.misra.org.uk/forumdisplay.php?fid=132)
+---- Thread: Rule 3-1-1 and constant declarations (/showthread.php?tid=691)



Rule 3-1-1 and constant declarations - MarkCotton - 18-11-2009

I have been using PCLint to analyse code which have constants defined in header files e.g.

const uint8 PLD_READ_VERIFICATION_BYTE_4 = 7;

PCLint claims that this violates rule 3-1-1. Is this a true interpretation of this rule or are constants permitted in header files?

Mark.


Re: Rule 3-1-1 and constant declarations - jbezem - 19-11-2009

IMHO, yes, in a strict sense this is a violation. Even if it is a constant, the construct is a definition, and it depends (among others) on the compiler whether the object will occupy storage. You could also create a pointer to such an object, in which case it has to occupy storage.
The compliant way to provide such constants would be to provide a declaration
extern const uint8 PLD_READ_VERIFICATION_BYTE_4;
in a header file, and provide one C file with the definition you provided.
Alternatively, you could also define a documented exception and remain compliant, albeit using a deviations documentation.

Be aware that providing constant definitions in a header file makes you rely on a linker property (outside of the strict scope of the C/C++ Standards), called the "Omitted Storage Class Model" (For C, see Harbison/Steele 5th edition, section 4.8), a property that is common for linkers to have, but several linkers can also be configured to support a different model.
Note that the above described 'compliant way' will produce identical results using any model.

HTH,

Johan


Re: Rule 3-1-1 and constant declarations - misra cpp - 11-10-2016

The ODR does not apply to const declarations as they have internal linkage, not external (the definition of the ODR explicitly says it only applies to objects with external linkage). So the examples quoted are compliant.

The first paragraph of the rationale will be replace with the following in "MISRA C++:2008 Technical Corrigendum 1":

"It shall be possible to include a header file into multiple translation units without violating the One Definition Rule. See section 6.3.2 for an explanation of the ODR."