(轉)C++程序調用C函數
轉自:http://blog.csdn.net/ustcgy/archive/2009/12/23/5063082.aspx
這種需求很多,又因為C++和C是兩種完全不同的編譯鏈接處理方式,所以要稍加處理.總結大致有兩大類實現方法.
文中給出的是完整的,具體的,但又最基本最簡單的實現,至于理論性的東西在網上很容易搜索的到.
一.通過處理被調用的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
二. 通過處理調用的C++文件
恢復a.h文件為一般性C頭文件,在aa.cpp文件中extern包含a.h頭文件或函數.
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 攀升 閱讀(3027) 評論(0) 編輯 收藏 引用 所屬分類: C/C++