Cmake - Can a shared library executable be linked with a relative path at runtime?

Suppose I have this:

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

      

Stages of creation:

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. When I test with:

ldd exec

      

output string:

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

      

This line of output is my question, is it possible to get:

libmylib.so => ./libmylib.so

      

so whenever I move the executable, I can move the shared library with it. If possible, how can I do it using cmake?

+3


source to share


3 answers


When you run the ldd

app's shared library to check for dependencies, it always prints absolute paths. But if you use -rpath

oprtion along with a variable $ORIGIN

, everything will work as you expect. You can move the executable and shared library, delete the original build directory and you can still run the application.

This is how you can do it using 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)

      

+3


source


Just add your CMakefiles.txt



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

      

+4


source


I had to put curly braces around $ {ORIGIN} and add the library path for the link:

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)

      

0


source







All Articles