Advertisement
obernardovieira

relative path library (linux)

Apr 5th, 2014
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.36 KB | None | 0 0
  1. While you can set LD_LIBRARY_PATH to let the dynamic linker know where to look, there are better options. You can put your shared library in one of the standard places, see /etc/ld.so.conf (on Linux) and /usr/bin/crle (on Solaris) for the list of these places
  2.  
  3. You can pass -R <path> to the linker when building your binary, which will add <path> to the list of directories scanned for your shared library. Here's an example. First, showing the problem:
  4.  
  5. libtest.h:
  6.  
  7. void hello_world(void);
  8.  
  9. libtest.c:
  10.  
  11. #include <stdio.h>
  12. void hello_world(void) {
  13. printf("Hello world, I'm a library!\n");
  14. }
  15.  
  16. hello.c:
  17.  
  18. #include "libtest.h"
  19. int main(int argc, char **argv) {
  20. hello_world();
  21. }
  22.  
  23. Makefile (tabs must be used):
  24.  
  25. all: hello
  26. hello: libtest.so.0
  27. %.o: %.c
  28. $(CC) $(CFLAGS) -fPIC -c -o $@ $<
  29. libtest.so.0.0.1: libtest.o
  30. $(CC) -shared -Wl,-soname,libtest.so.0 -o libtest.so.0.0.1 libtest.o
  31. libtest.so.0: libtest.so.0.0.1
  32. ln -s $< $@
  33. clean:
  34. rm -f hello libtest.o hello.o libtest.so.0.0.1 libtest.so.0
  35.  
  36. Let's run it:
  37.  
  38. $ make
  39. cc -fPIC -c -o libtest.o libtest.c
  40. cc -shared -Wl,-soname,libtest.so.0 -o libtest.so.0.0.1 libtest.o
  41. ln -s libtest.so.0.0.1 libtest.so.0
  42. cc hello.c libtest.so.0 -o hello
  43. $ ./hello
  44. ./hello: error while loading shared libraries: libtest.so.0: cannot open shared object file: No such file or directory
  45.  
  46. How to fix it? Add -R <path> to the linker flags (here, by setting LDFLAGS).
  47.  
  48. $ make clean
  49. (...)
  50. $ make LDFLAGS="-Wl,-R -Wl,/home/maciej/src/tmp"
  51. (...)
  52. cc -Wl,-R -Wl,/home/maciej/src/tmp hello.c libtest.so.0 -o hello
  53. $ ./hello
  54. Hello world, I'm a library!
  55.  
  56. Looking at the binary, you can see that it needs libtest.so.0:
  57.  
  58. $ objdump -p hello | grep NEEDED
  59. NEEDED libtest.so.0
  60. NEEDED libc.so.6
  61.  
  62. The binary will look for its libraries, apart from the standard places, in the specified directory:
  63.  
  64. $ objdump -p hello | grep RPATH
  65. RPATH /home/maciej/src/tmp
  66.  
  67. If you want the binary to look in the current directory, you can set the RPATH to $ORIGIN. This is a bit tricky, because you need to make sure that the dollar sign is not interpreted by make. Here's one way to do it:
  68.  
  69. $ make CFLAGS="-fPIC" LDFLAGS="-Wl,-rpath '-Wl,\$\$ORIGIN'"
  70. $ objdump -p hello | grep RPATH
  71. RPATH $ORIGIN
  72. $ ./hello
  73. Hello world, I'm a library!
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement