Clarification for 7-3-1: extern "C++"

Moderators: david ward, misra cpp

Post Reply
anj
Posts: 1
Joined: Tue Dec 09, 2014 10:55 am
Company: ZF Friedrichshafen AG

Clarification for 7-3-1: extern "C++"

Post by anj » Thu Apr 28, 2016 5:21 pm

For headers included by other C and C++ headers it is vital to use extern "C++".
But the rule implicitly forbids it by only allowing 3 kind of top level declarations.

Is it really intended to use this as the only compliant way:

Code: Select all

extern "C"
{
  extern "C++"
  {
    namespace MY_API
    {
    }
  }
}

dg1980
Posts: 109
Joined: Wed Apr 27, 2016 2:33 pm
Company: Elektrobit Automotive GmbH

Re: Clarification for 7-3-1: extern "C++"

Post by dg1980 » Fri Apr 29, 2016 11:43 am

I have to disagree, 7-3-1 is not the problem here, 16-2-1 is (see http://www.misra.org.uk/forum/viewtopic ... 1549#p3031)
Typically, in mixed C/C++ applications, you require extern "C" in the C Header only, because the C Module is compiled with a C Compiler and the C++ Module with a C++ Compiler.
If the C Header is checked with MISRA C++ (because the C++ module is), you break 16-2-1 (illustration below).

legacy.h

Code: Select all

#ifndef LEGACY_H
#define LEGACY_H

#ifdef __cplusplus// MISRA C 2012 compliant, but non-compliant with MISRA C++ 16-2-1
extern "C" {// compliant with MISRA C++ 7-3-1
#endif

void foo(void);

#ifdef __cplusplus// MISRA C 2012 compliant, but non-compliant with MISRA C++ 16-2-1
}
#endif

#endif
legacy.c

Code: Select all

#include "legacy.h"
/* no extern "C" required*/
void foo(void)
{
}
main.cpp

Code: Select all

#include "legacy.h"// compliant, no extern "C" required either

int main(void)
{
  foo();
  return 0;
}
I think MISRA has not put much thought into mixed C/C++ scenarios.

misra cpp
Posts: 148
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: Clarification for 7-3-1: extern "C++"

Post by misra cpp » Tue Oct 11, 2016 10:55 am

The preferred solution is as suggested by dg1980, with a deviation for the 16-2-1 violation
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.7 Declarations (C++)”