Use ld -soname
:
$ mkdir dir1 dir2
$ gcc -shared -fPIC -o dir1/func.so func1.c -Wl,-soname,func.so
$ gcc -shared -fPIC -o dir2/func.so func2.c -Wl,-soname,func.so
$ gcc test.c dir1/func.so
$ ldd a.out
linux-vdso.so.1 => (0x00007ffda80d7000)
func.so => not found
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f639079e000)
/lib64/ld-linux-x86-64.so.2 (0x00007f6390b68000)
$ LD_LIBRARY_PATH='$ORIGIN/dir1:$ORIGIN/dir2' ./a.out
hello world
$ LD_LIBRARY_PATH='$ORIGIN/dir2:$ORIGIN/dir1' ./a.out
No print
-Wl,-soname,func.so
(isso significa que -soname func.so
é passado para ld
) incorpora o atributo SONAME
de func.so
na saída. Você pode examiná-lo por readelf -d
:
$ readelf -d dir1/func.so
Dynamic section at offset 0xe08 contains 25 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000000e (SONAME) Library soname: [func.so]
...
Vinculado a esse func.so
com SONAME
, a.out
tem isso no atributo NEEDED
:
$ readelf -d a.out
Dynamic section at offset 0xe18 contains 25 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [func.so]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
...
Sem -Wl,-soname,func.so
, você receberá o seguinte por readelf -d
:
$ readelf -d dir1/func.so
Dynamic section at offset 0xe18 contains 24 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
...
$ readelf -d a.out
Dynamic section at offset 0xe18 contains 25 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [dir1/func.so]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
...