C++調用C函數

來源:互聯網
上載者:User

標籤:需要   clu   函數   aqi   main   nbsp   目錄   c++   利用   

為了防止無良網站的爬蟲抓取文章,特此標識,轉載請註明文章出處。LaplaceDemon/ShiJiaqi。

http://www.cnblogs.com/shijiaqi1066/p/6349243.html

 

 

有一個程式,代碼目錄如下:

.
|-- calc
| |-- calc.c
| `-- calc.h
`-- main.cpp

假如main.cpp需要調用calc.h中的函數(calc.c是c代碼)

傳統C編程中需要#include "calc/calc.h"後,聲明函數,然後調用。

但是由於main.cpp是個C++代碼。以C方式的調用,g++編譯器無法通過編譯。

 

解決方案一:
若calc中代碼量很小,或代碼是自己寫的可以直接利用c++相容c的特性,把calc.c改成calc.cpp。即可編譯。

 

解決方案二:
在calc.h中的每個函數最前面添加:extern "C"

比較簡單的方案是:

extern "C" {     void fun1(int arg1);     void fun2(int arg1, int arg2);     void fun3(int arg1, int arg2, int arg3); }

 

若不確定當前編譯環境是C還是C++,可以這樣:

#ifdef __cplusplus extern "C" {#endifvoid fun1(int arg1); void fun2(int arg1, int arg2); void fun3(int arg1, int arg2, int arg3);#ifdef __cplusplus }#endif

 

 

解決方案三:
若別人已經寫好的標頭檔,我們無法修改,怎麼辦?重寫一個專門被c++用的標頭檔即可。

例:編寫標頭檔 cpp_calc.h

extern "C" {#include "calc.h"; }

 

 

 

 

 

為了防止無良網站的爬蟲抓取文章,特此標識,轉載請註明文章出處。LaplaceDemon/ShiJiaqi。

http://www.cnblogs.com/shijiaqi1066/p/6349243.html

 

C++調用C函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.