最近需要在由纯c语言编写的代码中调用C++的动态库,在网上找了一些资料,现在总结下解决方法。
主要的思想就是将C++的动态库再封装一层,在这一层编写C语言的函数api,这API中使用C++动态库提供的类;
具体例子如下:
1,假如C++动态库包含如下代码:
//myclass.h
#ifndef _MYCLASS_H
#define _MYCLASS_H
class MyClass
{
public:
void print();
};
#endif
//myclass.cc
#include <iostream>
#include "myclass.h"
using namespace std;
void
MyClass::print()
{
cout << "MyClass::print() called" << endl;
}
编译链接生成动态库:libmyclass.so
g++ myclass.cc -shared -o libmyclass.so -I./ -fPIC
2,封装libmyclass.so中类的接口,生成libmyfunc.so
//myfunc.h
#ifndef _MYFUNCTION_H
#define _MYFUNCTION_H
#ifdef _cplusplus
extern "C" {
#endif
void myprint();
#ifdef _cplusplus
}
#endif
#endif
//myfunc.c
#include "myclass.h"
#ifndef _cplusplus
#define _cplusplus
#include "myfunc.h"
#endif
void
myprint()
{
MyClass mc;
mc.print();
}
编译链接生成动态库(C语言接口):
g++ myfunc.c -shared -o libmyfunc.so -L./ -lmyclass -fPIC -Xlinker -rpath=./
3,测试libmyfunc.so中提供的接口
//main.c
#include "myfunc.h"
int
main(int argc, char **argv)
{
myprint();
}
编译链接生成可执行代码:
gcc main.c -o main -lmyfunc -L./ -I. -Xlinker -rpath=./
执行main文件,输出如下:
MyClass::print() called
ok,大功搞成!!
注意事项:
1,注意myfunc.so必须是用g++来生成的,如果使用gcc,会不识别其中的类(这个解释不一定正确)
2,注意myfunc.h中_cpluscplus的用法,因为myfunc.h被main.c和myfunc.c两个文件用到,而extern仅被g++能够识别,
【同理 可以使用 ar rcs libmyclass.a my.o 编译 静态库】
-------静态库 在编译的时候 会出现 delete ,new, operator 等操作符没有定义 需要在gcc 时候加入-lstdc++ 链接上c++基础库 。