Page 1 of 1

Rule 3-1-1 and constant declarations

Posted: Wed Nov 18, 2009 6:08 pm
by MarkCotton
I have been using PCLint to analyse code which have constants defined in header files e.g.


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


Re: Rule 3-1-1 and constant declarations

Posted: Thu Nov 19, 2009 7:54 am
by jbezem
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.



Re: Rule 3-1-1 and constant declarations

Posted: Tue Oct 11, 2016 10:28 am
by misra cpp
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."