7

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?

buck
  • 1,502
  • 1
  • 20
  • 23

2 Answers2

11

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.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
1

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.

totowtwo
  • 2,101
  • 1
  • 14
  • 21