Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to add a C++ namespace to all symbols from a C library?

Tags:

c++

c

namespaces

I'm modifying a large C++ project, which defines in one of its main headers an enum FooBar. That enum gets included everywhere, and sadly is not namespaced.

From that project I'd like to use a C library, which unfortunately also defines an enum FooBar in the same global namespace.

I can't change the library implementation, and it's difficult to rename or namespace the enum in the C++ project because it's used all over the place.

So ideally I would add a namespace to all symbols coming from the C library. I have tried something like:

namespace c_library_foo {
#include <c_library_foo.h>
}

...
c_library_foo::c_library_function()
...

and that works fine as far as compilation is concerned, but of course the linker then fails to resolve the symbols from the library as the namespace is not in the implementation.

like image 433
Johan Bilien Avatar asked Dec 03 '10 23:12

Johan Bilien


2 Answers

Well I found the solution about 2s after posting this. Adding extern "C" makes it drop the namespace when resolving the symbols, and fixes my problem. Something like:

namespace c_library_foo {
extern "C" {
#include <c_library_foo.h>
}
}

...
c_library_foo::c_library_function()
...
like image 175
Johan Bilien Avatar answered Sep 22 '22 11:09

Johan Bilien


Nope. Supporting namespaces in C++ requires name mangling. The symbols emitted by the C library aren't name mangled (beacuse that doesn't happen in C). You need to rename the C++ enum rather than the C enum.

like image 41
Billy ONeal Avatar answered Sep 18 '22 11:09

Billy ONeal