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
#2
extern "C" only affects linkage, and MISRA C++:2023 rules do not place any limits on their contents.

The intention of 6.0.3 is to allows extern "C" to be used at global scope so that use can be made to declarations/definitions in headers from other  C-compatible languages. There is an expectation that they will not be used to add objects at global scope that would otherwise be disallowed by 6.0.3.

The wording of this rule is under review for a future version, to see if it needs to be more explicit what is allowed in an extern "C" block.
Posted by and on behalf of
the MISRA C++ Working Group
Reply


Forum Jump:


Users browsing this thread: 1 Guest(s)