我有一个.lib文件,我没有源代码。
我需要一个导出的函数,但是我用C编写,函数是C ++名称错误的。我不能写extern "C"
,因为我没有源代码。
如何在没有源代码的情况下链接损坏的函数并切换到C ++?
答案 0 :(得分:12)
制作C ++包装器:
<强> wrapper.cpp:强>
#include "3rdparty.hpp"
extern "C" int foo(int a, int b)
{
return third_party::secret_function(a, b);
}
<强> consumer.c:强>
extern int foo(int, int);
// ...
构建:(例如,使用GCC)
g++ -o wrapper.o wrapper.cpp
gcc -o consumer.o consumer.c
g++ -o program consumer.o wrapper.o -l3rdparty
答案 1 :(得分:5)
在这些函数上编写自己的C ++包装器,并使用extern "C"
声明包装器函数。
我不知道其他任何方式。
答案 2 :(得分:1)
可以从c程序中调用.lib文件中的受损名称。如果您链接的.lib是稳定的,而不是不断重新编译/更新,则此解决方案可能适合您。
我对Windows并不熟悉,但是How to See the Contents of Windows library (*.lib)或其他搜索应该显示如何从.lib获取此信息
在输出中搜索函数的名称,大多数修改将保留名称完整,只需用各种其他信息装饰它。
将该名称放在C代码中,并附上解释性注释......
答案 3 :(得分:1)
让我们假设您有一个.c文件(FileC.c),并且希望调用在.cpp(FileC ++。cpp)中定义的函数。让我们在C ++文件中将函数定义为:
void func_in_cpp(void)
{
// whatever you wanna do here doesn't matter what I am gonna say!
}
现在请执行以下步骤(以便能够从中调用上述功能 .c文件):
1)使用常规的C ++编译器(或www.cpp.sh),编写一个包含您的函数名称(func_in_cpp)的非常简单的程序。编译程序。例如。
$ g++ FileC++.cpp -o test.o
2)查找函数的错误名称。
$ nm test.out | grep -i func_in_cpp
[ The result should be "_Z11func_in_cppv" ]
3)转到您的C程序并做两件事:
void _Z11func_in_cppv(void); // provide the external function definition at the top in your program. Function is extern by default in C.
int main(void)
{
_Z11func_in_cppv(); // call your function to access the function defined in .cpp file
}