linux cmake分别指定编译/运行时动态库链接路径

1 背景

在树莓派上开发执行程序,需要用到opencv,curl,jsoncpp等库函数支持,apt-get安装好后,编译执行正常。但是执行程序挪到别的板子上,都要apt-get安装这些库,才能正常运行,每安装个板子都要联网装一遍这些环境就太麻烦了。(当然也可以用静态库编译)
linux cmake分别指定编译/运行时动态库链接路径_第1张图片

所以需要拷贝出能用的so,与应用程序一起拷贝到新板子上,运行时加载我们的so。
linux cmake分别指定编译/运行时动态库链接路径_第2张图片

2 cmake原本配置

find_package( OpenCV REQUIRED )
if (NOT OpenCV_FOUND)
    message(FATAL_ERROR "opencv Not Found!")
else()
endif (NOT OpenCV_FOUND)
include_directories(${OpenCV_INCLUDE_DIRS})
link_directories(
  ${OpenCV_Install}/lib
)
target_link_libraries(main ncnn ${OpenCV_LIBS}  jsoncpp curl)

可以看的target_link_libraries链接时都是使用系统默认的地址,这些库都是在/usr/lib,/usr/local/lib这些路径下的。

3 指定链接路径

把我们需要用的库,全部拷贝出来,统一放在一个lib目录下

###################################################################################################################
set(OPENCV_DYNAMIC_LIBS  "${CMAKE_CURRENT_SOURCE_DIR}/../lib")       # 动态 opencv native 库路径
add_library(libopencv_core SHARED IMPORTED )
set_target_properties(libopencv_core PROPERTIES   IMPORTED_LOCATION "${OPENCV_DYNAMIC_LIBS}/libopencv_core.so")
add_library(libopencv_highgui SHARED IMPORTED )
set_target_properties(libopencv_highgui PROPERTIES   IMPORTED_LOCATION "${OPENCV_DYNAMIC_LIBS}/libopencv_highgui.so")
add_library(libopencv_imgproc SHARED IMPORTED )
set_target_properties(libopencv_imgproc PROPERTIES   IMPORTED_LOCATION "${OPENCV_DYNAMIC_LIBS}/libopencv_imgproc.so")
add_library(libopencv_video SHARED IMPORTED )
set_target_properties(libopencv_video PROPERTIES   IMPORTED_LOCATION "${OPENCV_DYNAMIC_LIBS}/libopencv_video.so")

set(mOpenCV_LIBS  libopencv_core libopencv_highgui  libopencv_imgproc libopencv_video)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fopenmp ")
target_link_libraries(main ${mOpenCV_LIBS} )

类似上面,添加好所有需要的库,链接的时候就能找得到自定义路径lib下面的库了

4 指定运行时加载的库

只需要再cmake路径下加上如下:

SET(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) 
SET(CMAKE_INSTALL_RPATH "\${ORIGIN}/lib") #指定运行时动态库的加载路径,ORIGIN指运行文件所在目录

${ORIGIN}是指运行程序所在目录,如果你的lib放在其它路径下,你就改为你的路径即可

你可能感兴趣的:(linux cmake分别指定编译/运行时动态库链接路径)