开发者

problem wrapping extern "C" library in a namespace

I am using a C library (libgretl) from C++ and some of its functions conflict with my code, so I wanted to wrap it in a namespace, like this:

namespace libgretl {
extern "C" {
    #include <gretl/libgretl.h>
}}

However, this does not compile, I get "undefined" errors from gcc files (using mingw32 with gcc 4.5.2 on Windows). The first errors come from the following code block of file c++/cstddef:

_GLIBCXX_BEGIN_NAMESPACE(std)
  using ::ptrdiff_t;
  using ::size_t;
_GLIBCXX_END_NAMESPACE

开发者_C百科where the macros expand respectively to namespace std { and }. There are more errors after these.

Omitting the extern "C" directive does not help. Using an anonymous namespace reduces the amount of errors, but it still won't compile.

My question is therefore if there is some way to include such a C library and place its functions into a namespace, without changing the gcc or the library's source files?

Thanks.

Michal


You can't do it. Namespaces are not just source code decorations, they are mangled to object symbols by compiler.

Native C function foo() in library will be available by symbol _foo in object file, but calling bar::foo() will generate reference to, for example, @N3barfoo. As result, linker error will occur.

You may create "proxy" functions in separate source file, including original library header only in this source and putting all proxy functions to namespace.


You don't get to simply wrap a namespace around an external declaration and have it appear within that namespace... the item (function, global) must have been built within that namespace from the start. Since C doesn't support namespace resolution, this could not have been the case.

You need to change your own code to accommodate this library, unless you're willing to chante the library itself.

In order to refer to a non-namespace'd item that conflicts with your own namespace'd item, refer to ::item().


I guess the C library was compiled as C, which means namespaces are not included and not supported in the compiled code. Thus, your compiled C library cannot be in a namespace. Altering the header by encapsulating the include will not change that.

You can still encapsulate your own code in a namespace.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜