Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Rule about extern "C" and missing exceptions
#1
Currently, MISRA C++:2023 mentions "extern C" as part of the following rules:
  • title of Rule 6.0.3 (The only declarations in the global namespace should be main, namespace declarations and extern "C" declarations),
  • exception 2 of Rule 10.2.1,
  • amplification and rationale of Rule 18.4.1 and
  • as part of different examples (e.g., in Rule 19.0.3)

However, until now there is no rule provided that limits the keywords etc. can be "safely" used inside of an extern "C" block.

Wouldn't that be helpful?

Examples:
  • what happens when I define a namespace inside of an extern "C" block?
  • what happens when I define or declare (accidentally) a class in an extern "C" block?
  • what happens when I use a C++ reference in a function signature like "int foo(int& in_out)"?
  • Basics: the C compiler does not know extern "C". Consequently, it should be surrounded by ´#ifdef __cplusplus´ and ´#endif´.
  • ...

What about exceptions for extern "C" in the rules
  • 11.3.1 (Variables of array type should not be declared) as in an extern C block a std::array is not available.
  • 10.2.2 (Unscoped enumerations should not be declared) - notice that for 10.2.1 an exception si defined

Code example (https://godbolt.org/z/EG7Y9dxdh):
Code:
// some header.h - shared between C and C++

#ifdef __cplusplus
#include <cstdint>
#else
#include <stdint.h>
#endif

#ifdef __cplusplus
extern "C" {
#endif

  typedef int MyInt;  /* likely OK */

  void foo();  /* likely not OK */

  struct X { int a; };  /* is this OK? */ 

  struct Y { int32_t b; };  /* or this? */ 

  struct Z { char c[3]; };  /* or this? */ 

  namespace dummy {  /* and this? */
 
    class C {  /* or this - note: maybe the #ifdes __cplusplus guard is missing ...  */
    public:
      int val{2};
    };

  }

#ifdef __cplusplus
}
#endif


// c++ code

int main() {
 
  dummy::C c1;

  return c1.val;
}
Reply


Messages In This Thread
Rule about extern "C" and missing exceptions - by kth - 04-05-2026, 04:24 PM

Forum Jump:


Users browsing this thread: 2 Guest(s)