Search code examples
cshared-librariesdynamic-linkingfpic

different function address in PIC shared library


I have a file ptr.c as

a@po:~/code/link_load$ cat ptr.c
int test()
{
     printf("in test1 %p\n",&test);
    return 0;
}

I created a shared lib as

a@po:~/code/link_load$ gcc -fPIC -c ptr.c
a@po:~/code/link_load$ gcc -shared -o libptr.so ptr.o                                                                       

Then I call test from two programs p1.c and p2.c, both call test and p1.c sleeps after calling test to ensure both executables are active together.

Since text section is shared I was expecting the address of test function to be same.

But it is not, why?

EDIT: I guess the address printed is virtual address. If that is true then it maps to actual address, which would be same for both p1 and p2.


Solution

  • A single file (e.g, the text section of your library) can be mapped at a different virtual address in multiple processes, while still being shared. That's what's going on here.