实现此目的的一种方法是使用 dladdr:
共享对象的代码:
$ cat so.c
#include <stdio.h>
#include <dlfcn.h>
void test_so_func()
{
Dl_info info;
if (dladdr(test_so_func, &info))
{
printf("Loaded from path = %s\n", info.dli_fname);
}
printf("hello\n");
}
主要执行代码:
$ cat test.c
void test_so_func();
int main() {
test_so_func();
return 0;
}
生成文件:
$ cat Makefile
test: test.o libso.so
gcc test.o -o $@ -Wl,-L.,-lso,-rpath,'$$ORIGIN'
clean:
-rm -f libso.so test.o test
libso.so: so.c
gcc -D_GNU_SOURCE=1 -fPIC -shared $< -o $@ -lc -ldl
test.o: test.c
gcc -fPIC -c $< -o $@
我们来编译一下吧!
$ make
gcc -fPIC -c test.c -o test.o
gcc -D_GNU_SOURCE=1 -fPIC -shared so.c -o libso.so -lc -ldl
gcc test.o -o test -Wl,-L.,-lso,-rpath,'$ORIGIN'
测试这个二进制文件。
$ ./test
Loaded from path = /spare/scratch/1564054710/libso.so
hello
验证 libso.so 确实说的是实话。
$ ldd ./test
linux-vdso.so.1 => (0x00007ffdf55d5000)
libso.so => /spare/scratch/1564054710/./libso.so (0x00007fbcc4602000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fbcc4238000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fbcc4034000)
/lib64/ld-linux-x86-64.so.2 (0x00007fbcc4804000)
这个答案的功劳在于https://github.com/mingwandroid https://github.com/mingwandroid