Linux安裝g++
yum install gcc-c++ libstdc++-devel
在其他資料上增加了過程中遇到的問題。
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;
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
————————————————
版權聲明:本文為CSDN部落客「zhxjlbs」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。
原文連結:https://blog.csdn.net/zhxjlbs/article/details/54972069