开发者

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

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开发者_C百科 the implementation.


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


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜