简体   繁体   English

C vs C ++中的typedef和struct命名空间

[英]typedef and struct namespaces in C vs C++

I am trying to use some old C libraries in some new C++. 我试图在一些新的C ++中使用一些旧的C库。

The library's header files use D. Hanson's "C Interfaces and Implementations" implementation-hiding idiom of: 该库的头文件使用D. Hanson的“ C接口和实现”实现隐藏式成语:

#define T MyAST 

typedef struct T *T;

Near as I can tell, this compiles with C because in C struct names and typedef names are in different namespaces but it does not compile with C++ ( extern "C" { #include "MyAST.h" } ) evidently because typedef and struct names are in the same namespace. 几乎可以告诉我,它可以使用C进行编译,因为在C中,结构名称和typedef名称位于不同的命名空间中,但显然不能使用C ++进行编译( extern "C" { #include "MyAST.h" } ),显然是因为typedef和结构名称在同一个命名空间中。

conflicting declaration 'typedef struct MyAST* MyAST'

I think I'm doomed to move the struct def into the headers and give up using the technique but I really don't want to (this idiom is used in a lot of code, some mine, some not) and thought I'd check here to see if anyone has any insight. 我想我注定要把struct def移到头文件中并放弃使用该技术,但是我真的不想(很多语言中使用了这个习惯用法,有些是我的,有些则没有),并且我想在这里查看是否有人有任何见识。

PS: If you don't know the idiom, it lets you keep the struct definition in the implementing C file and then users of the interface ( MyAST.h ) can't reach into the struct, they must use your functions in the implementation. PS:如果您不了解该惯用语,则可以将结构定义保留在实现的C文件中,然后接口的用户( MyAST.h )无法访问该结构,则他们必须在实现中使用您的函数。

Honestly if the only purpose here is to use some old libraries (which we'll presume won't be updated), I'd create a glue layer between your C++ and the old libraries. 老实说,如果这里的唯一目的是使用一些旧库(我们假定不会更新),我将在您的C ++和旧库之间创建一个胶合层。 Just write a small amount of wrapper code that's compiled in C to use the old libraries, and provide a C interface that compiles in C++ to your new C++ code. 只需编写少量在C中编译的包装器代码以使用旧库,并提供一个C接口即可将C ++编译为新的C ++代码。

Having the same name mean two different things can only cause confusion among future maintainers, so I would try to isolate the interface code to a few source files. 具有相同的名称意味着两个不同的事物只会在将来的维护者之间引起混乱,因此我将尝试将接口代码隔离到几个源文件中。

Finally, while I can appreciate wanting to separate the interface from the implementation at some point you have to trust your code users to not flagrantly violate the conditions of the library and just code it in an obvious way rather than going to paranoid lengths to hide struct definitions away. 最后,尽管我希望在某些时候将接口与实现分开,但您必须相信您的代码用户不要公然违反库的条件,而只是以一种明显的方式对其进行编码,而不是使用偏执的长度来隐藏结构定义消失了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM