在其他资料上增加了过程中遇到的问题。
so文件为动态链接库文件,与windows下的dll文件相当,Linux下系统so文件一般保存在/usr/lib中。
下面就说明一下如何生成c++程序的so文件,以及如何在c++程序中调用该so文件
==========test.h===========
#ifdef __cplusplus //
extern "C"
{
#endif
class Test{
public:
int hello(int i);
};
int helloT(int j);
#ifdef __cplusplus
}
#endif
==========test.cpp===========
#include"test.h"
#include<iostream>
using namespace std;
int Test::hello(int i){
if(i>3)
cout<<"hello Class Test>3"<<endl;
else
cout<<"hello Class Test<3"<<endl;
return 0;
}
int helloT(int j){
Test *t=new Test();
t->hello(j);
return 0;
}
编译test.cpp文件
g++ -shared -fpic -lm -ldl -o libtest.so test.cpp
其中,so文件名必须以lib开头。编译具体指令请参考帮助文档
编译调试test.cpp文件
gcc -ggdb3 -Wall -shared -fpic -o libtest.so test.cpp
==========main.cpp===========
动态链接:
#include <stdio.h>
#include <dlfcn.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
/*
需要用到的函数
dlopen()
dlerror()
dlsym()
dlclose()
都存储在头文件dlfcn.h中
*/
int main() {
void *handle = dlopen("./libtest.so", RTLD_LAZY); //该处的./libtest.so表示so文件的存放位置,RTLD_LAZY是指示位
if(!handle) {
printf("open lib error\n");
cout<<dlerror()<<endl;
return -1;
}
typedef int (*hello)(int);//该处的函数与文件test.h中需调用的函数保持一致
hello h= (hello)dlsym(handle, "helloT");// helloT为test.h中调用函数的名字,dlsym返回一个函数指针
if(!h) {
cout<<dlerror()<<endl;
dlclose(handle);
return -1;
}
int i;
cin>>i;
(*h)(i);//用函数指针形式调用函数
dlclose(handle);
return 0;
}
in#include <stdio.h>
#include <stdlib.h>
#include "filter.h"
int main() {
printf("example\n");
int lengthData = 10;
//int Data[2][10] = { 1 };
int *buf =(int*) malloc(20*4);
int **Data = &buf;
int Ecg_filter_V5[10]={0},Ecg_filter_V1[10]={0};
int Fs = 128;
printf("11111\n");
// int **datatemp = (int**)Data;
int result = 0;
printf("start filter\n");
result = filter(Data, lengthData, Ecg_filter_V5, Ecg_filter_V1, Fs);
if (result != 1)
{
printf("filter error\n");
}
else
{
printf("filter OK\n");
}
return 0;
}
编译main.cpp文件
g++ main.cpp -ldl -o main
编译调试main.cpp文件
gcc -ggdb3 -Wall -o test main.c -Llib -lfilter
执行./main
调试 main
gdb -q test
单步执行 s
run