简体   繁体   English

cmake - 是否可以在运行时将可执行文件链接到具有相对路径的共享库?

[英]cmake - Is it possible to link executable to shared library with relative path at runtime?

Lets say I have this: 让我说我有这个:

../project_dir
    main.cpp
    mylib.cpp
    mylib.h

Building steps will be: 构建步骤将是:

g++ -c mylib.cpp -o mylib.o
g++ -shared -o libmylib.so mylib.o
g++ -L$(pwd) -Wl,-rpath='$ORIGIN' -o exec main.cpp -lmylib

exec will be my binary executable output. exec将是我的二进制可执行输出。 When I testing with: 当我测试时:

ldd exec

the output line is: 输出线是:

libmylib.so => /full/path/to/build/directory/libmylib.so (0x00007f75fdd1f000)

That output line is my question, is it possible to get: 那个输出行是我的问题,有可能得到:

libmylib.so => ./libmylib.so

so whenever I move the executable file, I can move the shared library along with it. 因此,每当我移动可执行文件时,我都可以随身携带共享库。 If it is possible, how to do this with cmake? 如果有可能,如何用cmake做到这一点?

Juste add in your CMakefiles.txt Juste添加了你的CMakefiles.txt

set(CMAKE_INSTALL_RPATH "$ORIGIN")
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE) # only if you want copy from the build tree

When you launch ldd to check your app shared library dependencies, it always prints absolute paths. 当您启动ldd以检查应用程序共享库依赖项时,它始终打印绝对路径。 But if you are using the -rpath oprtion together with the $ORIGIN variable, everything will work as you expect. 但是,如果你使用的是-rpath一起oprtion与$ORIGIN变量,一切都会如你所期望的工作。 You can move the executable and the shared library, remove the original build directory and you will still be able to launch your app. 您可以移动可执行文件和共享库,删除原始构建目录,您仍然可以启动您的应用程序。

This is how you can do it using cmake : 这是你如何使用cmake来做到这一点:

project(myapp)
cmake_minimum_required(VERSION 2.8)

set(APP_SRC main.cpp)
set(LIB_SRC mylib.cpp)

link_directories(${CMAKE_CURRENT_BINARY_DIR})

SET(CMAKE_EXE_LINKER_FLAGS
          "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath -Wl,$ORIGIN")

add_library(mylib SHARED ${LIB_SRC})

add_executable(${PROJECT_NAME} ${APP_SRC})

target_link_libraries(${PROJECT_NAME} mylib)

I had to put curly braces around ${ORIGIN} and add path for the library to link: 我不得不在$ {ORIGIN}周围加上大括号,并为要链接的库添加路径:

SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L${CMAKE_BINARY_DIR} -lmyLibrary -Wl,-rpath -Wl,${ORIGIN}")
set(CMAKE_INSTALL_RPATH "${ORIGIN}")
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM