将cpp文件封装成 so 文件并调用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/AP1005834/article/details/79998358

一、前言

    本篇记录下将 Cpp文件打包成so 文件,并在其他cpp文件中作调用

二、将cpp文件编译为so文件

在文件夹 cpp1 下创建a.h a.cpp b.h b.cpp 如下:

//a.h
#ifndef A_H_
#define A_H_

#include "b.h"

class A
{
  public:
	A(){}
	~A(){}

	void showImg(char* path);

};

#endif
//a.cpp
#include "a.h"

void A::showImg(char* path)
{
	B b;
	b.showImg(path);
}
//b.h
#ifndef B_H_
#define B_H_

#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"

class B
{
  public:
	void showImg(char* path);
};

#endif
//b.cpp
#include "b.h"

void B::showImg(char* path)
{
	cv::Mat img = cv::imread(path);
	cv::imshow("Img",img);
	cv::waitKey(0);
}

编译出个so文件,将a.h a.cpp 编译出so 文件

sudo g++ -fpic -shared -o libA.so a.cpp b.cpp -I /usr/local/include -L /usr/local/lib -lopencv_core -lopencv_highgui

四、调用libA.so 文件

在文件夹 cpp2 下创建main.cpp如下:
//main.cpp
#include "a.h"

int main()
{
	char *path =(char*) "zxy.jpg";
	A a;
	a.showImg(path);
	return 0;
}
编译该main.cpp

sudo g++ -o main main.cpp -I ../cpp1/ -L ../cpp1/ -I /usr/local/include -L /usr/local/lib -lopencv_core -lopencv_highgui -lA

执行./main

出现./main: error while loading shared libraries: libA.so: cannot open shared object file: No such file or directory

找不到动态库,执行

export LD_LIBRARY_PATH=/home/zjy/testCpp/cpp1:$LD_LIBRARY_PATH,

运行./main,运行结果为:


猜你喜欢

转载自blog.csdn.net/AP1005834/article/details/79998358