Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problem wrapping extern "C" library in a namespace

Tags:

c++

namespaces

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

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

like image 852
Michal Kaut Avatar asked Aug 25 '11 09:08

Michal Kaut


2 Answers

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

like image 20
mah Avatar answered Oct 23 '22 21:10

mah


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.

like image 93
blaze Avatar answered Oct 23 '22 22:10

blaze