Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak-linking with static libraries

I have declared an external function with a GCC weak attribute in a .c file:

extern int weakFunction( ) __attribute__ ((weak));

Compiled object file has weakFunction defined as a weak symbol. Output of nm:

1791:         w weakFunction

I am calling the weak defined function as follows:

if (weakFunction != NULL)
{
    weakFunction();
}

When I link the program by defining the object files as parameters to GCC (gcc main.o weakf.o -o main.exe) weak symbols work fine. If I leave the weakf.o out of linking, the function address is NULL in main.c and the function won't be called.

Problem is, when weakf.o is inside a static library, for some reason the linker doesn't find the function and the function address always ends up being NULL. Static library is created with ar: ar rcs weaklibrary weakf.o

Anyone had similar problems?

like image 444
Jaakko L. Avatar asked Oct 14 '22 07:10

Jaakko L.


1 Answers

While I don't know the exact workings of weak symbols it looks like you are getting what you ask for: if no one else is forcing the weakFunction() to be present, main() won't either. To me this makes sense: if you are trying to write code which works with facility X present as well as without it, then you don't want your code to force X to be included in your build at all costs. It looks like "weak" is meant to ask if something is present, not to request that something is present. Maybe you can force inclusion of weak symbols with "-u weakFunction" as linker option in your case.

like image 120
slartibartfast Avatar answered Oct 19 '22 02:10

slartibartfast