C調用C++
C調用C++鏈接庫:
1.編寫C++代碼,編寫函數的時候,需要加入對C的接口,也就是extern “c"
2.由於C不能直接用"class.function”的形式調用函數,所以C++中需要為C寫一個接口函數。例如本來要調用student類的talk函數,就另外寫一個cfun(),專門建一個student類,並調用talk函數。而cfun()要有extern聲明
3.我在練習中就使用在C++頭文件中加extern ”c”的方法。而C文件要隻需要加入對cpp.h的引用
4.詳細見如下代碼:
student是一個類,裏邊有talk函數,就輸出一句話而已
cpp.cpp與cpp.h是兩個C++代碼,包含對C的接口
最後用C代碼:helloC.c來測試結果
student.cpp
- #include <iostream>
- using namespace std;
- #include "student.h"
- void student::talk(){
- cout<<"I am Kenko"<<endl;
- }
- #ifndef _STUDENT_
- #define _STUDENT_
- class student{
- public:
- void talk();
- };
- #endif
cpp.h:
- #ifndef _CPP_
- #define _CPP_
- #include "student.h"
- #ifdef __cplusplus
- extern "C" {
- #endif
- void helloCplusplus();
- #ifdef __cplusplus
- }
- #endif
- #endif
- #include <iostream>
- using namespace std;
- #include "cpp.h"
- student stu;
- void helloCplusplus(){
- cout<<"helloC++"<<endl;
- stu.talk();
- }
- void helloCplusplus2(){
- cout<<"helloC++"<<endl;
- }
- #include <stdio.h>
- #include "cpp.h"
- int main(){
- helloCplusplus();
- return 0;
- }
我這次練習是直接在xp環境下,在CMD命令行方式用gcc,g++來編譯的。
1.編譯C++代碼,成為鏈接庫
g++ -shared -o libccall.so cpp.cpp student.cpp (libccall.so為庫名)
2.編譯C代碼:g++ helloC.c ./libccall.so。這裏一定要用g++,如果用gcc會出錯,因為gcc編譯C++文件才會自動調用g++,但如果對象直接就是C文件就不會調用g++了。

來源:https://blog.csdn.net/w397090770/article/details/7744454
最後更新:2017-04-02 16:48:08