用C的typedef和struct命名空间VS C ++ [英] typedef and struct namespaces in C vs C++

查看:237
本文介绍了用C的typedef和struct命名空间VS C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用一些老的C库在一些新的C ++。

I am trying to use some old C libraries in some new C++.

库的头文件使用D. Hanson的C接口和实现 implementation-躲在成语:

The library's header files use D. Hanson's "C Interfaces and Implementations" implementation-hiding idiom of:

#define T MyAST 

typedef struct T *T;

近,我可以告诉,这与编译C,因为在C结构的名称和typedef名称在不同的命名空间,但它并没有使用C ++编译(的externC{#包括MyAST.h } ),这显然是因为的typedef和struct的名字都在同一个命名空间。

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.

conflicting declaration 'typedef struct MyAST* MyAST'

我觉得我注定要在结构DEF进入页眉和放弃使用的技术,但我真的不希望(这个成语在很多code,一些矿,有的不是用)我想我会在这里检查,看看是否任何人有任何见解。

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.

PS:如果你不知道这个成语,它可以让你保持结构定义在实施C文件,然后该接口的用户( MyAST.h )不能伸入结构,就必须在实现使用功能。

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.

推荐答案

老实说,如果这里的唯一目的就是利用一些旧库(我们将presume将不会被更新),我想创建一个你的C ++和老库之间的胶合层。只是写在C编译使用旧包装的库code少量,并提供C接口,在C ++编译你的新的C ++ code。

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. 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.

具有相同名称的意思是两个不同的东西,只能导致未来的维护者的混淆,所以我会尽量接口code隔离到一些源文件。

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.

最后,虽然我可以AP preciate想接口从实现在某些时候,你必须不公然违反图书馆的条件,相信你的code用户和独立只是code将其在一个明显的方式,而不是去偏执长度躲结构定义了。

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.

这篇关于用C的typedef和struct命名空间VS C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆