Extern "C" library in namespace

I use the C library (libgretl) from C ++, and some of its functions conflict with my code, so I would like to wrap it in a namespace, for example:

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 block of C ++ / cstddef file code:

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

where macros expand accordingly to namespace std { and } . After that, more errors appear.

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

So my question is, is there a way to include such a C library and put its functions in the namespace without modifying the gcc source files or libraries?

Thanks.

Michal

+6
source share
3 answers

You cannot do this. Namespaces are not only the scenery of the source code, they are distorted by object symbols by the compiler.

The Native C function foo () in the library will be accessible by the _foo symbol in the object file, but a call to bar :: foo () will generate a link to, for example, @ N3barfoo. As a result, a linker error will occur.

You can create proxy functions in a separate source file, including the source library header in this source only, and put all proxy functions in the namespace.

+7
source

You cannot just wrap a namespace around an external declaration and display it inside that namespace ... an element (function, global) must be created in this namespace from the very beginning. Since C does not support namespace resolution, this could not be.

You need to modify your own code to host this library, unless you want to migrate the library yourself.

To refer to an element that does not belong to a namespace that conflicts with your own namespace, see ::item() .

+2
source

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

You can still encapsulate your own code in the namespace.

+1
source

Source: https://habr.com/ru/post/895845/


All Articles