20140806 交換兩個數 extern “C”用法

來源:互聯網
上載者:User

標籤:color   strong   檔案   2014   ar   代碼   amp   c++   

1、交換兩個數

方法1、a+b有可能越界

a=a+b;

b=a-b;

a=a-b;

方法二、不會越界

a=a^b

b=a^b;

a=a^b;

 

2、extern “C”用法

自己總結:

1、C++語言引用C語言函數時(void fun(int a,int b),void fun(int a,float b)),由於C++有重載功能,編譯器按C++的方式編譯該函數後產生的名字五花八門(_fun_int_int和_fun_int_float)。

2、而被調用的c語言函數庫,或者.c檔案產生的.obj檔案中函數的名字只有一個(_fun)。

3、這樣,c++模組在調用void fun(int a,int b)時,就會以_fun_int_int的名字在c函數庫(.dll檔案)和.obj中匹配,但是這兩個中的函數的名字卻是_fun,所以就找不到該函數,也就無法調用了。

(1)在C++中引用C語言中的函數和變數(葉的理解:應該是調用.dll時吧),在包含C語言標頭檔(假設為cExample.h)時,需進行下列處理:

extern "C" {#include "cExample.h"}

而在C語言的標頭檔中,對其外部函數只能指定為extern類型,C語言中不支援extern "C"聲明,在.c檔案中包含了extern "C"時會出現編譯語法錯誤。

筆者編寫的C++引用C函數例子工程中包含的三個檔案的原始碼如下:

/* c語言標頭檔:cExample.h */

#ifndef C_EXAMPLE_H

#define C_EXAMPLE_H

extern int add(int x,int y);     //注:寫成extern "C" int add(int , int ); 也可以

#endif

/* c語言實現檔案:cExample.c */

#include "cExample.h"

int add( int x, int y )

{

return x + y;

}

// c++實現檔案,調用add:cppFile.cpp

extern "C"

{#include "cExample.h"  }     //註:此處不妥,如果這樣編譯通不過(葉的理解:原因是函數實現在.c檔案,不是.DLL)。換成 extern "C" int add(int , int ); 可以通過。

 

int main(int argc, char* argv[])

{

add(2,3);

return 0;

}

如果C++調用一個C語言編寫的.DLL時,當包括.DLL的標頭檔或聲明介面函數時,應加extern "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.