typedef and struct namespaces in C vs C++

…衆ロ難τιáo~ 提交于 2019-12-24 02:16:31

问题


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

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

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

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.

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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/10240577/typedef-and-struct-namespaces-in-c-vs-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!