一、使用c++封装动态库
参考文献:http://www.linuxidc.com/Linux/2012-09/70502.htm
1.新建test类
1.1新建 test.cpp 文件
代码如下:
#include<iostream>
extern "C"
int myadd(int a, int b)
{
return a + b;
}
备注:extern"C" 必须有,不然会报undefined symbol: myadd.
1.2新建test.h文件
代码如下:
#ifndef _TESTSO_H
#define_TESTSO_H
extern"C"
{
intmyadd(int a, int b);
typedefint myadd_t(int, int); // myadd function type
}
#endif// _TESTSO_H
备注:test.h文件可以没有,因为test.cpp也没有#include <test.h>,再说myadd()函数也不是类的成员函数。
2.编译
g++ -shared -fPIC -o test.so test.cpp
备注1:
-fPIC:生成位置无关目标代码,适用于动态连接;
-L path:表示在path目录中搜索库文件,如-L.表示在当前目录;
-I path:表示在path目录中搜索头文件;
-o file:制定输出文件为file;
-shared:生成一个共享库文件;
备注2:
编译多个cpp文件:
g++ -shared-fPIC -o demo.so demo.cpp CCNF_patch_expert.cpp LandmarkDetectorFunc.cppLandmarkDetectorModel.cpp LandmarkDetectorUtils.cppLandmarkDetectorParameters.cpp LandmarkDetectionValidator.cpp Patch_experts.cppPAW.cpp PDM.cpp SVR_patch_expert.cpp stdafx.cpp$(pkg-config opencv --cflags --libs) $(/usr/lib/x86_64-linux-gnu/libboost_filesystem.so;/usr/lib/x86_64-linux-gnu/libboost_system.so)-I /usr/include/boost -L /usr/lib/x86_64-linux-gnu/ -I boost_system –l boost_filesystem
(在使用上面命令代码编译时,先将代码放到txt中,写成一行,最后在赋值到命令行进行编译,不然可能会出错)
,最好是写个makefile文件来编译。
3. C++方式调用库
3.1新建main.cpp
代码如下:
#include <stdio.h>
#include <dlfcn.h> //必须有
#include <iostream>
#include"test.h" // for dynamic library函数
int main(int argc, char*argv[])
{
if (2 != argc)
{
return-1;
}
const char *soname =argv[1];
void *so_handle = dlopen(soname,RTLD_LAZY); // 载入.so文件