Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using C-style struct/typedef from within C++

I have a project that is mixing C and C++. In a C header file, I have code like this:

typedef struct mystruct* mystruct;
struct mystruct {
    // whatever struct needs
};

And to use this in the C++ file, I am doing:

extern "C" {
#include "mystruct.h"
}

So you see that I am creating an opaque pointer using the same names. This is fine in C but not in C++ (because of the requirement to instantiate using the struct keyword in C but not in C++). However, I get an error (conflicting declarations) when trying to compile the C++ code. I thought that using the extern "C" would make the compiler treat the C header as C, but it seems to still be using it as C++. Is there any explanation for what is happening here?

like image 513
buck Avatar asked Jul 12 '11 20:07

buck


2 Answers

I thought that using the extern "C" would make the compiler treat the C header as C

No. The only thing that extern "C" does is control name mangling. The code is still compiled as C++ (though things that require mangled names, such as namespaces or templates, won’t work). In particular, the rule concerning struct identifiers still applies.

like image 137
Konrad Rudolph Avatar answered Sep 28 '22 02:09

Konrad Rudolph


extern "C" enforces C linkage, as opposed to mangled C++ linkage. extern "C" does not enforce full C compliance such as dynamically sizable arrays, etc.

like image 44
totowtwo Avatar answered Sep 28 '22 04:09

totowtwo