C調用C++連結庫

來源:互聯網
上載者:User

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:

1#include <iostream>
2using namespace std;
3#include "student.h"
4void student::talk(){
5 cout<<"I am Kenko"<<endl;
6}
7
8
9

   student.h:

1#ifndef _STUDENT_
2#define _STUDENT_
3
4class student{
5 public:
6   void talk();
7};
8
9#endif

  cpp.h:

 1#ifndef _CPP_
 2#define _CPP_
 3
 4#include "student.h"
 5#ifdef __cplusplus
 6extern "C" {
 7#endif
 8void helloCplusplus();
 9#ifdef __cplusplus
10}
11#endif
12
13#endif

  cpp.cpp:

 1#include <iostream>
 2using namespace std;
 3
 4#include "cpp.h"
 5student stu;
 6void helloCplusplus(){
 7cout<<"helloC++"<<endl;
 8stu.talk();
 9}
10
11void helloCplusplus2(){
12cout<<"helloC++"<<endl;
13}

 

  helloC.c:

 

#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++了。

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.