MISRA Discussion Forums
Rule 6.2.1: non-inline constexpr variables in headers? - 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++:2023 guidelines (https://forum.misra.org.uk/forumdisplay.php?fid=188)
+---- Forum: 4.6 Basic concepts (https://forum.misra.org.uk/forumdisplay.php?fid=192)
+---- Thread: Rule 6.2.1: non-inline constexpr variables in headers? (/showthread.php?tid=1716)



Rule 6.2.1: non-inline constexpr variables in headers? - cgpzs - 22-11-2024

Hi, 

Consider the following example:

Code:
// foo.h
constexpr int kFoo = 123;

inline int foo(int x)
{
  return x * kFoo;
}

// tu1.cpp
#include "foo.h"
int tu1() { return foo(1); }

// tu2.cpp
#include "foo.h"
int tu2() { return foo(2); }

Does the function "foo" violate Rule 6.2.1 in this context, given that kFoo is not a C++17 inline variable? 
Or would it violate 6.2.1 only if kFoo were ODR-used (for example, passed by reference)?

Thanks!


RE: Rule 6.2.1: non-inline constexpr variables in headers? - misra cpp - 20-12-2024

The rule requires that ODR isn't violated, as defined by the standard. In general, its impractical for us explicitly enumerate all the way ODR can be violated.

In general, you need to consult [basic.def.odr]. However, our reading of the standard is that the answer to your first question is No (your example does not violate ODR)

Other refs:
https://en.cppreference.com/w/cpp/language/definition
https://eel.is/c++draft/basic.link#:linkage,inline_and

We also agree that the answer to your second question is Yes


RE: Rule 6.2.1: non-inline constexpr variables in headers? - cgpzs - 20-12-2024

Thank you for the clarification!


RE: Rule 6.2.1: non-inline constexpr variables in headers? - misra cpp - 07-02-2025

This thread now closed