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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With