开发者

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

开发者 https://www.devze.com 2023-03-19 14:46 出处:网络
I have a project that is mixing C and C++.In a C header file, I have code li开发者_运维问答ke this:

I have a project that is mixing C and C++. In a C header file, I have code li开发者_运维问答ke 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?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消