gcc weak symbol with __attribute((weak)) handling with shared library

426 Views Asked by At

write file, one with the weak file and another with the normal symbol. Below are the contents of the files: where weak_ex() is the definition declared with weak symbol.

bgl-ads-2997:~/weak_symbol > cat m.c

#include <stdio.h>
#include "weak.h"
void main (){
    printf ("weak = %d\n", weak_ex());
}

bgl-ads-2997:~/weak_symbol > cat weak.c

int __attribute__((weak)) weak_ex()
{
    return 1;
}

bgl-ads-2997:~/weak_symbol > cat strong.c

int weak_ex()
{
    return 10;
}

bgl-ads-2997:~/weak_symbol > cat weak.h

int weak_ex();

So with the above definitions weak symbol will return 1, and strong will return 10.

Then I compiled them as below:

gcc -g -c -o m.o m.c
gcc -g -c -o weak.o weak.c
gcc -g -c -o strong.o strong.c
gcc -shared -fpic -o libstrong.so strong.o
gcc -shared -fpic -o libweak.so weak.o

then linked them and executed as below:

  1. using only the object file:

     bgl-ads-2997:~/weak_symbol > gcc  m.o weak.o strong.o -L`pwd` -Wl,-R`pwd` -o shared
    
     bgl-ads-2997:~/weak_symbol > ./shared 
    
     weak = 10
    

In this case weak symbol is masked, and strong signal is taken as expected.

  1. link with weak symbol in object file and strong symbol in shared object.

     bgl-ads-2997:~/weak_symbol > gcc -lstrong m.o weak.o -L`pwd` -Wl,-R`pwd` -o shared
    
     bgl-ads-2997:~/weak_symbol > ./shared 
    
     weak = 1
    

In this case weak symbol is not getting replaced.

Seems symbol are resolved in compilation time and not as part of execution, not not considering the shared Expecting this also to print 10 but not so, So is this the expected behaviour? is there a way to get the weak symbol replaced from the shared library?

0

There are 0 best solutions below