Duplicate of the following question: C function conflict

你好,
在我当前的项目中,我必须使用某种接口(interface)库。函数名称由该接口(interface)给出,该函数的作用是开发人员选择。据我所知,一个项目将使用此功能,并且在进行编译时,您选择lib及其功能。我想做的是通过包装另一个并在mein函数中调用它来同时使用现有的lib和我的lib:

otherlib:

int function1 (int a) {
// do something
}

mylib:
int function1 (int a) {
//my code here
    otherlib::function1(a);
}

问题是我无权访问另一个库,而另一个库没有任何 namespace 。我已经试过了
namespace old {
    #include "otherlib.h"
}

然后在我的函数中通过old::function1调用旧函数。只要它是唯一的头文件,它就可以工作。 lib将其符号导出回全局空间。也有点像
namespace new {
    function1 (int a) {
        ::function1(a);
    }
}

没用。最后但并非最不重要的一点是,我尝试了ifdefs并定义了建议的here

但我没有成功。

任何想法如何解决这个问题?提前致谢。

编辑:我既无权访问旧库,也无权使用两个库中的项目。

EDIT2:至少旧库是静态库

最佳答案

C中的命名空间使用库名称前缀来解决,例如:

libfoo-> foo_function1
libbar-> bar_function1

这些前缀是实际的 namespace 。所以如果你写libbar

int bar_function1(int a) {
     function1(a);
}

这是解决问题的方法。

C有 namespace ---它们只是称为前缀;)

另一个选择是通过动态加载库来执行各种肮脏的技巧,例如:
h1=dlopen("libfoo.so")
foo_function1=dlsym(h1,"function1")

h2=dlopen("libbar.so")
bar_function1=dlsym(h2,"function1")

08-06 00:27
查看更多