(轉(zhuǎn))C++程序調(diào)用C函數(shù)
轉(zhuǎn)自:http://blog.csdn.net/ustcgy/archive/2009/12/23/5063082.aspx
這種需求很多,又因?yàn)镃++和C是兩種完全不同的編譯鏈接處理方式,所以要稍加處理.總結(jié)大致有兩大類實(shí)現(xiàn)方法.
文中給出的是完整的,具體的,但又最基本最簡(jiǎn)單的實(shí)現(xiàn),至于理論性的東西在網(wǎng)上很容易搜索的到.
一.通過(guò)處理被調(diào)用的C頭文件
a.h:
#ifndef __A_H
#define __A_H
#ifdef __cplusplus
extern "C" {
#endif
int ThisIsTest(int a, int b);
#ifdef __cplusplus
}
#endif
#endif
a.c:
#include "a.h"
int ThisIsTest(int a, int b) {
return (a + b);
}
aa.h:
class AA {
public:
int bar(int a, int b);
};
aa.cpp:
#include "a.h"
#include "aa.h"
#include "stdio.h"
int AA::bar(int a, int b){
printf("result=%d\n", ThisIsTest(a, b));
return 0;
}
main.cpp:
#include "aa.h"
int main(int argc, char **argv){
int a = 1;
int b = 2;
AA* aa = new AA();
aa->bar(a, b);
delete(aa);
return(0);
}
Makefile:
all:
gcc -Wall -c a.c -o a.o
gcc -Wall -c aa.cpp -o aa.o
gcc -Wall -c main.cpp -o main.o
g++ -o test *.o
二. 通過(guò)處理調(diào)用的C++文件
恢復(fù)a.h文件為一般性C頭文件,在aa.cpp文件中extern包含a.h頭文件或函數(shù).
a.h:
#ifndef __A_H
#define __A_H
int ThisIsTest(int a, int b);
#endif
aa.cpp:
extern "C"
{
#include "a.h"
}
#include "aa.h"
#include "stdio.h"
int AA::bar(int a, int b){
printf("result=%d\n", ThisIsTest(a, b));
return 0;
}
or
aa.cpp:
#include "aa.h"
#include "stdio.h"
extern "C"
{
int ThisIsTest(int a, int b);
}
int AA::bar(int a, int b){
printf("result=%d\n", ThisIsTest(a, b));
return 0;
}
posted on 2010-03-08 15:23 攀升 閱讀(3028) 評(píng)論(0) 編輯 收藏 引用 所屬分類: C/C++