我们需要建立一个.cpp文件和一个头文件,例如:
HBShell.cpp:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "HrvBike.h" #include "HBShell.h" hrvBikeInterface *pInterface = NULL; //int isOk = 0; void initHrvInterface() { if (pInterface == NULL) { pInterface = new hrvBikeInterface(); } } //hrvBike.calHrvParamsMain(spath, despath, age, gender); void calHrvParamsMain(char* spath, char* despath, int age, int gender) { if (pInterface != NULL) { pInterface->calHrvParamsMain(spath, despath, age, gender); } }HBShell.h:
#ifndef HB_SHELL #define HB_SHELL extern void initHrvInterface(); extern void calHrvParamsMain(char* spath, char* despath, int age, int gender); #endif 编译动态库,考虑到代码是c++,所以编译指令最好用g++编译(否则再c调用的时候,可能会出现问题) 指令:g++ HRVAnalysis.cpp HRVBasic.cpp hrvBike.cpp HRVParameters.cpp HBShell.cpp -fPIC -m64 -shared -o libHrv.so
会在当前目录下生成libHrv.so的动态库。
编写调用该动态库的代码,该代码我们用c文件来实现,例如: test.c: #include <stdio.h> #include "HBShell.h" int main() { initHrvInterface(); calHrvParamsMain("/usr/shareBike/hrvBike1.1/data/ecgdata.rr", "/usr/shareBike/hrvBike1.1/data/", 18, 1); if (getHrvFlag() == 1) { printf("getHighestHr---->%d\n", getHighestHr()); printf("getLowestHr---->%d\n", getLowestHr()); printf("getAvrHr---->%d\n", getAvrHr()); printf("getStressScore---->%d\n", getStressScore()); printf("getStressLevel---->%d\n", getStressLevel()); } return 0; }这里需要注意,一定要将动态库里的HBShell.h这个头文件包含进来。否则会报错。
生成test.c的可执行文件,需要用指令:g++ test.c -lHrv -L. -I. -o test
需要注意,这里请用g++编译,否则会造成c库和c++库函数引用的混乱。从而产生undefined reference之类的错误。
这里会生产test这样一个可执行文件,通过指令./test即可正常执行。
参考文档: http://www.linuxidc.com/Linux/2013-11/93010.htm