Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

linker - How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...