This may be a stupid question, but if I compile a shared library using g++ on one distribution of Linux, and then move those libraries as object files via flash drive to another computer with the exact same Linux distro and version of g++ will I still be able to link those libraries in my source files on the second machine?
I’m asking because I don’t have the permissions to install the necessary libraries before compiling on the second machine, so it’d be easier for me to just compile them on my own computer and upload the compiled object files via flash drive to the second machine
Advertisement
Answer
Let me explain you with some example.
suppose i have binary named myapp
in my machine X
and i want to run it in another machine Y
but when i run then it show me some error like
./myapp: error while loading shared libraries: libcgicc.so.5: cannot open shared object file: No such file or directory
This means I’m using a library that isn’t on the other machine. Of course, I could try installing all the same libraries on Y as there are on X. But i have’t permission to do. Then our alternative is to statically link libraries with our program.
On Y
, run the command ldd myapp
. This will give something like:
libpthread.so.0 => /lib/tls/libpthread.so.0 (0xf7f77000) libdl.so.2 => /lib/libdl.so.2 (0xf7f73000) libgd.so.2 => /usr/lib/libgd.so.2 (0xf7f26000) libcgicc.so.5 => not found <------------------------------------//this library missed libjpeg.so.62 => /usr/lib/libjpeg.so.62 (0xf7f08000) libpng12.so.0 => /usr/lib/libpng12.so.0 (0xf7ee4000)
Let’s go back to our compiling machine, machine X
, and see what ldd myapp
says there for libcgicc:
libcgicc.so.5 => /usr/lib/libcgicc.so.5 (0xb7f18000)
So on machine X
, the library we want is in /usr/lib. If we do ls /usr/lib/libcgicc*
we can see what versions of this library are available. On machine that is:
/usr/lib/libcgicc.a /usr/lib/libcgicc.la /usr/lib/libcgicc.so /usr/lib/libcgicc.so.5 /usr/lib/libcgicc.so.5.0.1
So there is a static version available,libcgicc.a
. If there were not a .a
version, we would need to get one – on debian/ubuntu
we could track it down by doing (as superuser):
apt-file search libcgicc.a
Now, all we need to do is relink
our program, replacing -lcgicc
with /usr/lib/libcgicc.a
. Now when we do ldd myapp
on either machine, we have no more missing libraries.
However, that doesn’t guarantee all libraries are exactly the same version. A frequent problem is libstdc++
for C++ code. If you see a message like this when trying to run your code:
./myapp: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.9′ not found (required by ./myapp)
Then you’ve got a version mismatch. This may be fixable by statically linking the libstdc++ library. Check what version of g++
you are using with g++ –version
, and then check for libstdc++.a
in:
/usr/lib/gcc/[platform-name]/[version]
(location may be different on your computer). Once you track this file down you can link it statically as before.