[cpp:GlobalNamespaceMembers][MISRA] Triggered by forward declarations in a mixed C/C++ environment

cpp:GlobalNamespaceMembers is being triggered by forward declarations.
I cannot put the forward declaration inside the namespace.

MISRA C++ Rule 7–3–1 does not specify “forward declarations” as an exception.
MISRA C++ Rule 3–2–2 and 3-2-3 seem like basic common sense to me.

The way I read this, forward declarations should still be allowed in a MISRA environment:
https://forum.misra.org.uk/thread-766-post-2420.html

I think this is indeed a false positive – or is there a way for this to satisfy the rule?

My C++ header file looks like this:


struct MyCStruct; // forward declaration

namespace MyNamespace
{
    class MyClass
    {
         MyCStruct* m_myCStructInstance;        
    };
}

in the .cpp, I then include the code for the C struct

SonarQube server 8.9.0, SonarScanner 4.6.1.2450, sonar.cfamily

Hello @Sidelobe,

If I understand correctly, you cannot put it because it is a C struct, not a C++ struct.
But the rule 7-3-1 allows C declarations in the global namespace. You should just write:

extern "C"
struct MyCStruct; // forward declaration

namespace MyNamespace {
    class MyClass    {
         MyCStruct* m_myCStructInstance;        
    };
}

But notice it would still be a violation of 3-2-3 (I don’t think it makes much sense, and it will most probably be amended in the next MISRA release), so you should actually write:

// In <MyCStructFwd.h>
struct MyCStruct; // forward declaration

// In your code
extern "C" {
#include <MyCStructFwd.h>
}

namespace MyNamespace {
    class MyClass    {
         MyCStruct* m_myCStructInstance;        
    };
}

Hope this helps!

1 Like

Thanks Loïc!

I was not aware that one could place extern "C" before a forward declaration. That is a nice fix in my situation and also adds valuable additional information (i.e. expressing this is a C type).

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.