C++调用C生成的动态库
tt
posted @ 2007年11月14日 05:28
in C语言编程
, 5016 阅读
看下面这个例子,其中add函数是用c编写的代码,而主函数是用c++编写的代码,将c代码编译成动态库,然后用c++调用。
add.h
#ifndef ADD_FILE_HEADER_INC
#define ADD_FILE_HEADER_INC
#include <stdio.h>
#include <malloc.h>
extern double
add (double a, double b);
#endif
#define ADD_FILE_HEADER_INC
#include <stdio.h>
#include <malloc.h>
extern double
add (double a, double b);
#endif
add.c
#include "add.h"
double
add (double a, double b){
return a+b;
}
double
add (double a, double b){
return a+b;
}
main.cxx
extern "C"
{
#include "add.h"
}
int
main()
{
double a=5.2, b=65.47;
double c=add(a,b);
printf("%lf\n", c);
return 0;
}
{
#include "add.h"
}
int
main()
{
double a=5.2, b=65.47;
double c=add(a,b);
printf("%lf\n", c);
return 0;
}
用于编译的makefile如下:
makefile
main:main.o add.so
g++ -o main main.o ./add.so -g
add.so:add.c
gcc -fpic -shared -g -o add.so add.c -I ./
main.o:main.cxx
gcc -c main.cxx -I ./
clean:
rm *.so *.o main
g++ -o main main.o ./add.so -g
add.so:add.c
gcc -fpic -shared -g -o add.so add.c -I ./
main.o:main.cxx
gcc -c main.cxx -I ./
clean:
rm *.so *.o main
需要注意的是,在生成可执行文件时,用的编译命令为g++, 而不是gcc,如果用gcc编译将出现如下错误:
umain.o:(.eh_frame+0x11): ndefined reference to `__gxx_personality_v0'
2022年11月08日 19:00
Not everyone know all information about a celebrity and their net worth which changes every day according to their fame and investment but you can follow the info on celeb height wiki which is available for everyone.