I have 2 files:
strong.cc
#include <stdio.h>
void foo(){
printf("Strong is here\n");
}
weak.cc
#include <stdio.h>
void __attribute__((weak)) foo();
void foo(){
printf("Weak is here\n");
}
and then my main.cc
#include <stdio.h>
extern void foo();
int main(int argc, char* argv[]) {
foo();
return 0;
}
First, I compiled the strong.c and weak.c to generate strong.so and weak.so respectively with
g++ strong.cc -o libstrong.so -shared -fPIC
g++ weak.cc -o libweak.so -shared -fPIC
Then, I compiled the main.c
g++ -c main.cc -o main.o
Lastly, I linked the main.o with the 2 other .so files
g++ main.o -L. -lweak -strong
What printed is:
Weak is here
Then when I reversed the order of linking to
g++ main.o -L. -lstrong -lweak
What printed is:
Strong is here
I searched for this, and I think it is a limitation (https://en.wikipedia.org/wiki/Weak_symbol) But I am constrained to have the linking in that order. So, is there any workaround or hack to overcome this limitation? Or is there a bug tracking page for this in GNU community that sets expectations on when will it be fixed?
I also tried the linking without the -l with
g++ main.o libsim2.so libsim.so
but I got the same results.
I tried a lot of options with g++ like --start-group <strong_lib> --end-group and --whole-archive and tried the version script with
{
global:
*;
local:
*WeakSymbol*;
};
But none of them worked and always the weak function overrides the strong function as it came first in the linking order.