views:

62

answers:

1

I'm following the C++ Cookbook tutorial on static and dynamic library linking with g++. I can build the binary fine, but when I run it I get the error

./hellobeatles: error while loading shared libraries: libjohnpaul.so: cannot open shared object file: No such file or directory

I used the command : g++ -o hellobeatles hellobeatles.cpp -L ../johnpaul/ -L ../georgeringo/ -ljohnpaul -lgeorgeringo

The program builds and runs fine if I explicitly list the path like : g++ -o hellobeatles hellobeatles.cpp ../johnpaul/libjohnpaul.so ../georgeringo/libgeorgeringo.so

Am I linking to the libaries incorrectly in the first command? Or is there some configuration setting I need to muck with?

I'm running an Ubuntu 9.10 guest vm in VirtualBox if that matters, and here's the -v Using built-in specs. Target: x86_64-linux-gnu Configured with: ../src/configure -v --with-pkgversion='Ubuntu 4.4.1-4ubuntu9' --with-bugurl=file:///usr/share/doc/gcc-4.4/README.Bugs --enable-languages=c,c++,fortran,objc,obj-c++ --prefix=/usr --enable-shared --enable-multiarch --enable-linker-build-id --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.4 --program-suffix=-4.4 --enable-nls --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --disable-werror --with-arch-32=i486 --with-tune=generic --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu Thread model: posix gcc version 4.4.1 (Ubuntu 4.4.1-4ubuntu9)

+1  A: 

The dynamic linker expects to find shared libraries in /usr/lib, /lib, /usr/local/lib, and possibly a few other places. It will certainly not look for them in ../johnpaul/.

If the libraries are intended to be installed into a global location, then just install them there.

Otherwise, you must tell the dynamic linker where to find them.

A better approach is to add them to RPATH encoded into the executable:

 g++ -o hellobeatles hellobeatles.cpp \
     -L ../johnpaul/ -L ../georgeringo/ -ljohnpaul -lgeorgeringo \
     -Wl,-rpath=/path/to/johnpaul:/path/to/georgeringo

Alternative (and less preferred) approach is to:

export LD_LIBRARY_PATH=/path/to/johnpaul:/path/to/georgeringo
Employed Russian