C++共享库:创建和使用

C++ Shared library: Creation and usage

本文关键字:创建 共享 C++      更新时间:2023-10-16

我正在尝试构建一个共享对象,以便以后使用其他项目中共享对象DoSomethingUseful()的函数。 它使用外部库以及我在多个项目中使用的一堆标头。

使用 CMake,我创建了一个项目 MySharedLib,其中包含一个名为library.h

#ifndef MYSHAREDLIB_LIBRARY_H
#define MYSHAREDLIB_LIBRARY_H

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cstdio>
// own header files
#include <header1.h>
#include <header2.h>
#define PI 3.14159265
//tesseract
#include <tesseract/baseapi.h>
#include <leptonica/allheaders.h>

//openCV 
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
//face detection
#include "opencv2/objdetect.hpp"
#include "opencv2/imgproc.hpp"
void DoSomethingUseul(int[] inparray);

#endif

library.cpp

#include "library.h"
void DoSomethingUseful(int[] inparray){...}

我的CMake文件是这样的:

cmake_minimum_required(VERSION 3.10)
project(MYSHAREDLIB)
find_package( OpenCV REQUIRED )
set(CMAKE_CXX_STANDARD 11)
set(MY_INCLUDE_DIR ../source/)
set(MY_OPENCV_CASCADES /opencvpath/openCV34/opencv/sources/data/haarcascades/)
include_directories(${MY_INCLUDE_DIR} ${MY_OPENCV_CASCADES} /usr/include)
link_directories(${MY_INCLUDE_DIR})
add_library(MYSHAREDLIB SHARED library.cpp library.h
${MY_INCLUDE_DIR}header1.cpp
${MY_INCLUDE_DIR}header1.h
${MY_INCLUDE_DIR}header2.cpp
${MY_INCLUDE_DIR}header2.h
)
set_target_properties(MYSHAREDLIB PROPERTIES VERSION 3.10)
set_target_properties(MYSHAREDLIB PROPERTIES SOVERSION 1)
target_link_libraries(MYSHAREDLIB lept tesseract ${OpenCV_LIBS})

*.so 文件是成功创建的,即使用 Clion,不会抛出任何错误,并且文件libMySharedLib.so在那里。

但是,当我想在另一个文件中使用该函数DoSomethingUseful()DoSomething.cpp

#include <iostream>
#include "library.h"
using namespace std;
int main()
{
int[2] myarray; myarray[0]=1; myarray[1] =2;
DoSomethingUseful(myarray);
return 0;
}

g++ -g -Wall -o DoSomething DoSomething.cpp -I ../source/ -L. libMYSHAREDLIB.so 

当我执行时

./DoSomething

我得到:

./DoSomething: error while loading shared libraries: libMYSHAREDLIB.so: cannot open shared object file: No such file or directory

之前,我在编译时没有-I ../source/产生:

In file included from DoSomething.cpp:8:0:
library.h:19:10: fatal error: header1.h: No such file or directory
#include <header1.h>

我发现许多线程通常都在处理此问题,并且我已经从这些问题中收集了很多有关共享对象的知识,并且还成功地从运行的各种教程中获取了示例。 但是,我没有成功开展自己的项目。

这只是众多问题之一,但我希望我能在这里得到帮助,也许还有一般提示。非常感谢您的任何帮助。

假设Linux(如果错误,请修改问题(。运行可执行文件时,共享库仅从/etc/ld.so.conf 中列出的路径加载。如果你想从其他地方加载(.(,你必须设置LD_LIBRARY_PATH环境变量,例如LD_LIBRARY_PATH=。 ./DoSomething