How can I share library between two program in c

↘锁芯ラ 提交于 2019-11-29 12:31:14

Code gets shared by the operating system, not only of shared libraries but also of executables of the same binary — you don't have to do anything to have this feature. It is part of the system's memory management.

Data will not get shared between the two processes. You would need threads in one process to share data. But unless you want that, just make sure both programs use exactly the same shared library file (.so file). Normally you won't have to think about that; it only might be important if two programs use different versions of a library (they would not get shared of course).

Have a look at the output of ldd /path/to/binary to see which shared libraries are used by a binary.

Read Drepper's paper How to Write Shared Libraries and Program Library HowTo

To make one, compile your code as position independent code, e.g.

 gcc -c -fPIC -O -Wall src1.c -o src1.pic.o
 gcc -c -fPIC -O -Wall src2.c -o src2.pic.o

then link it into a shared object

 gcc -shared src1.pic.o src2.pic.o -lsome -o libfoo.so

you may link a shared library -lsome into another one libfoo.so

Internally, the dynamic linker ld-linux.so(8) is using mmap(2) (and will do some relocation at dynamic link time) and what matters are inodes. The kernel will use the file system cache to avoid reading twice a shared library used by different processes. See also linuxatemyram.com

Use e.g. ldd(1), pmap(1) and proc(5). See also dlopen(3). Try

cat /proc/self/maps

to understand the address space of the virtual memory used by the process running that cat command; not everything of an ELF shared library is shared between processes, only some segments, including the text segment...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!