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

 ̄綄美尐妖づ 提交于 2020-01-03 13:33:07

问题


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.


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/4350756/is-it-possible-to-add-a-c-namespace-to-all-symbols-from-a-c-library

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!