Linux C語言調用C++動態鏈接庫
標簽: C調用C++庫
2014-03-10 22:56 3744人閱讀 評論(0) 收藏 舉報

版權聲明:本文為博主原創文章,未經博主允許不得轉載。
如果你有一個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?
- #include?<iostream>??
- using?namespace?std;??
- ??
- class?Myclass?{??
- public:??
- ????Myclass(){}??
- ????~Myclass(){}??
- ????void?Operation();??
- };??
- #include?"myclass.h"??
- using?namespace?std;??
- void?Myclass::Operation()??
- {??
- ????cout?<<?"Hi?my?name?is?sjin"?<<endl;??
- }??
3 interface.h
- #ifdef?__cplusplus??
- extern?"C"{??
- #endif??
- ??
- void?interface();??
- ??
- #ifdef?__cplusplus??
- }??
- #endif??
4 interface.cpp
- #include?"myclass.h"??
- #include?"interface.h"??
- ??
- #ifdef?__cplusplus??
- extern?"C"{??
- #endif??
- ??
- void?interface()??
- {??
- ????Myclass?obj;??
- ????obj.Operation();??
- }??
- ??
- #ifdef?__cplusplus??
- }??
- #endif??
5 main.c
- #include?"interface.h"??
- ??
- int?main()??
- {??
- ????interface();??
- ????return?0;??
- }??
具體編譯流程
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