linux平台中c代码调用c++动态库
2017-03-09 18:03
405 查看
首先,我们先需要添加一个外壳,外壳的功能是:将c++的类的方法进行包装,形成类似C语言的库函数
我们需要建立一个.cpp文件和一个头文件,例如:
HBShell.cpp:
HBShell.h:
编译动态库,考虑到代码是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:
这里需要注意,一定要将动态库里的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
我们需要建立一个.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
相关文章推荐
- linux的ubuntu上如何编译C和C++代码写的动态库,以及调用执行
- linux 下python 调用C++ .so如何debug c++代码
- lua调用C++动态库(windows平台)
- linux/eclipse/c++ 动态库的创立与调用
- Linux 平台相关代码的 C++ 解决方案
- X64 平台 C/C++调用汇编代码
- Linux 平台相关代码的 C++ 解决方案
- linux/eclipse/c++ 动态库的创立与调用
- Linux环境下android平台调试native代码, 从java debug 到C++ (NDK DEBUG)
- linux/eclipse/c++ 动态库的创立与调用
- Linux环境下android平台调试native代码, 从java debug 到C++ (NDK DEBUG)
- linux/eclipse/c++ 动态库的创立与调用
- Linux 平台相关代码的 C++ 解决方案
- Linux下通过java调用C/C++代码
- linux用c++调用动态库
- Linux环境下android平台调试native代码, 从java debug 到C++ (NDK DEBUG)
- Linux 平台相关代码的 C++ 解决方案
- Linux 平台相关代码的 C++ 解决方案
- C++ 定义适应不同平台调用不同代码的方法
- 关于Linux C++代码在Windows平台上的调试运行