Search code examples
c++ubuntulibraries.sorpath

Link libraries to linux biinary file in c++


I'm compiling a c++ program using g++ and i am using two libraries called libsdl2-dev and libsdl2-image-dev I installed both these libraries in my ubuntu machine with the commands apt install libsdl2-dev libsdl2-image-dev and when I compile the program everything works fine. Then I copied these libraries from /usr/lib/x86_64-linux-gnu/ to my working dir with the binary file to be able to give this folder to someone else. The problem comes when the user that hasn't installed these libraries tries to open my program by writing ./main (the binary file). Since he hasn't installed these libraries he would get an error like "can't open shared object: no such file or directory". This happens because the binary file looks for these libraries in /usr/lib etc...

What i need

I need that my binary file looks for these libraries in the same folder,and not in /usr/lib/x86 etc.., from what I read I have to do something like rpath

The IDE used is Sublime Text and the syntax used to compile all my files is this:

g++ -c src/*.cpp -std=c++14 -m64 -g -Wall -I include && g++ *.o -o bin/debug/main -lSDL2main -lSDL2 -lSDL2_image  && ./bin/debug/main`

Structure of folders

I got the project dir with and inside that i got 4 more directories, each one called: bin (with the debug subdirectory, where we got the final compile), include (with hpp files), res (with all textures), and src with all cpp files to compile, the other files are project files and .o files

I'm using Ubuntu 20.04-2 LTS and the same is for the other user's PC

Thanks in advance for any help!


Solution

  • That's because the dynamic linker loading runtime dependencies looks for them in some specified locations, which are "by default" your system library directories (where those libraries got installed by apt).

    The other user should ideally install those libraries too (which could be done "automatically" if you build a .deb package with proper dependencies)

    Otherwise you would have to change the runpath of your program by adding -Wl,-rpath='$ORIGIN', which makes the dynamic linker look for dependencies just where the binary is located.

    $ORIGIN here is a special variable meaning "this executable" which is what you wanted to achieve.

    see rpath and A description of RPATH $ORIGIN