0

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?

AJM
  • 1,317
  • 2
  • 15
  • 30
Deepak
  • 86
  • 9
  • `So is this the expected behaviour?` yes. Formatting tip: to make code blocks inside enumeration, use 8 spaces. – KamilCuk Dec 14 '20 at 12:57
  • is there a way to make it work? to replace the weak symbol with the a strong symbol from shared library? – Deepak Dec 14 '20 at 12:58

0 Answers0