Linux C语言调用C++动态链接库

如果你有一个c++做的动态链接库.so文件,而你只有一些相关类的声明,那么你如何用c调用呢,

C++创始人在编写C++的时候,C语言正盛行,他不得不让C++兼容C。C++最大的特性就是封装,继承,多态,重载。而这些特性恰恰是C语言所不具备的。至于多态,核心技术是通过虚函数表实现的,其实也就是指针。而对于重载,与C语言相比,其实就是编译方式不同而已: C++编译方式和C编译方式。对于函数调用,编译器只要知道函数的参数类型和返回值以及函数名就可以进行编译连接。那么为了让C调用C++接口或者是说C++调用C接口,就必须是调用者和被调用者有着同样的编译方式。这既是extern "C"的作用,extern “C”是的程序按照C的方式编译。

下面具体看下面的代码:

1、myclass.h 

  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. class Myclass {  
  5. public:  
  6.     Myclass(){}  
  7.     ~Myclass(){}  
  8.     void Operation();  
  9. };  
2、myclass.cpp

  1. #include "myclass.h"  
  2. using namespace std;  
  3. void Myclass::Operation()  
  4. {  
  5.     cout << "Hi my name is sjin" <<endl;  
  6. }  

3 interface.h

  1. #ifdef __cplusplus  
  2. extern "C"{  
  3. #endif  
  4.   
  5. void interface();  
  6.   
  7. #ifdef __cplusplus  
  8. }  
  9. #endif  

4 interface.cpp

  1. #include "myclass.h"  
  2. #include "interface.h"  
  3.   
  4. #ifdef __cplusplus  
  5. extern "C"{  
  6. #endif  
  7.   
  8. void interface()  
  9. {  
  10.     Myclass obj;  
  11.     obj.Operation();  
  12. }  
  13.   
  14. #ifdef __cplusplus  
  15. }  
  16. #endif  

5 main.c

  1. #include "interface.h"  
  2.   
  3. int main()  
  4. {  
  5.     interface();  
  6.     return 0;  
  7. }  

具体编译流程

1】首先生成动态库

  1. g++  myclass.cpp interface.cpp -fPIC -shared -o libtest.so  

2】将动态库拷贝的/usr/lib目录下

3】编译main.c

gcc main.c -L.  -ltest

4】运行./a.out



参考资料:

http://blog.csdn.net/feiyinzilgd/article/details/6723882

http://www.bdqn.cn/news/201309/11368.shtml
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值