I have a project that is mixing C and C++. In a C header file, I have code like this:
我有一个混合C和c++的项目。在C头文件中,我有如下代码:
typedef struct mystruct* mystruct;
struct mystruct {
// whatever struct needs
};
And to use this in the C++ file, I am doing:
要在c++文件中使用这个,我要做的是:
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?
你可以看到,我用相同的名字创建了一个不透明的指针。这在C中很好,但在c++中没有(因为需要在C中使用struct关键字来实例化,而不是在c++中)。然而,在尝试编译c++代码时,我得到了一个错误(冲突声明)。我认为使用extern“C”会使编译器将C header视为C,但它似乎仍将其作为c++使用。这里发生的事情有什么解释吗?
2 个解决方案
#1
11
I thought that using the
extern "C"
would make the compiler treat the C header as C我认为使用extern“C”时,编译器会将C header视为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.
不。外部“C”所做的唯一一件事就是控制姓名。代码仍然被编译为c++(尽管需要损坏名称的东西,比如名称空间或模板,不能工作)。特别是,关于结构标识符的规则仍然适用。
#2
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.
外部“C”执行C连接,而不是损坏的c++连接。extern“C”不强制执行完全的C一致性,例如动态大小的数组等。
#1
11
I thought that using the
extern "C"
would make the compiler treat the C header as C我认为使用extern“C”时,编译器会将C header视为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.
不。外部“C”所做的唯一一件事就是控制姓名。代码仍然被编译为c++(尽管需要损坏名称的东西,比如名称空间或模板,不能工作)。特别是,关于结构标识符的规则仍然适用。
#2
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.
外部“C”执行C连接,而不是损坏的c++连接。extern“C”不强制执行完全的C一致性,例如动态大小的数组等。