75

There is a laptop on which I have no root privilege.

onto the machine I have a library installed using configure --prefix=$HOME/.usr .

after that, I got these files in ~/.usr/lib :

libXX.so.16.0.0
libXX.so.16
libXX.so
libXX.la
libXX.a

when I compile a program that invokes one of function provided by the library with this command : gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX

xxx.out was generated without warning, but when I run it error like this was thrown:

./xxx.out: error while loading shared libraries: libXX.so.16: cannot open shared object file: No such file or directory , though libXX.so.16 resides there.

my clue-less assumption is that ~/.usr/lib wasn't searched when xxx.out is invoked. but what can I do to specify path of .so , in order that xxx.out can look there for .so file?

An addition is when I feed -static to gcc, another error happens like this:

undefined reference to `function_proviced_by_the_very_librar'

It seems .so does not matter even though -L and -l are given to gcc. what should I do to build a usable exe with that library?


For other people who has the same question as I did

I found a useful article at tldp about this.

It introduces static/shared/dynamic loaded library, as well as some example code to use them.

Community
  • 1
  • 1
Jokester
  • 5,501
  • 3
  • 31
  • 39

2 Answers2

122

There are two ways to achieve that:

  • Use -rpath linker option:

gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib

  • Use LD_LIBRARY_PATH environment variable - put this line in your ~/.bashrc file:

    export LD_LIBRARY_PATH=/home/user/.usr/lib

This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.

For a quick test, you can also do (in bash at least):

LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out

which has the advantage of not changing your library path for everything else.

pelya
  • 4,326
  • 2
  • 24
  • 23
5

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

Regolith
  • 2,944
  • 9
  • 33
  • 50
Ashit
  • 75
  • 1
  • 1
  • 11
    `LD_LIBRARY_PATH` is not for GCC, it is for runtime library loader (/lib/ld-linux.so.2 etc). GCC might not be installed at all for `LD_LIBRARY_PATH` to work. – pelya Apr 23 '18 at 20:46