gcc -c -Wall main.c
gcc -c -Wall -fPIC foo.c bar.c
gcc -shared foo.o -o libfoo.so
gcc -shared bar.o -o libbar.so
gcc -c -Wall -fPIC foobar.c //can be add to 2.
gcc -shared foobar.o -o libfoobar.so -L. -lfoo -lbar //ORIGINAL: note the lib is omitted
gcc -shared foobar.o -o libfoobar.so -L. -lfoo -lbar -Wl,-rpath,. //EDITED
// whenever creating the .so use -Wl,-rpath,. lib in that dir
gcc -o prog main.o -L. -lfoobar -Wl,-rpath-link=$(pwd) // let's not use this.
gcc -o prog main.o -L. -lfoobar -Wl,-rpath=$(pwd) // try this
gcc -o prog main.o -L. -lfoobar -Wl,-rpath,. //EDITED: oops = is not very compatible across OS's seems
# would error if we do not include LD PATH
./prog
./prog: error while loading shared libraries: libfoo.so: cannot open shared object file: No such file or directory
LD_LIBRARY_PATH=. ./prog
foo
bar
#EDITED. Should find the ld path at run time.
./prog
foo
bar
https://stackoverflow.com/a/49181161/2712045
ld aaa bbb ccc
===> gcc -Wl,aaa -Wl,bbb -Wl,ccc
=>gcc -Wl,aaa,bbb,ccc
Wl,-rpath,dir1,-rpath,dir2
~= -Wl,-rpath=dir1,-rpath=dir2
-Wl,-rpath,.
means -Wl,-rpath -Wl,.
Source: https://stackoverflow.com/a/6562437/2712045
PIC: This would work whether the code was at address 100 or 1000
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL CURRENT+10
...
111: NOP
Non-PIC: This will only work if the code is at address 100
100: COMPARE REG1, REG2
101: JUMP_IF_EQUAL 111
...
111: NOP
EDIT: In response to comment.
If your code is compiled with -fPIC, it's suitable for inclusion in a library - the library must be able to be relocated from its preferred location in memory to another address, there could be another already loaded library at the address your library prefers.