Weak link with static libraries

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

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

The compiled object file has a weak function, defined as a weak symbol. Output signal nm:

 1791: w weakFunction 

I call a weak defined function as follows:

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

When I link the program, defining object files as parameters for GCC ( gcc main.o weakf.o -o main.exe ), weak characters work fine. If I leave a weak .o signal from the link, the function address will be NULL in main.c and the function will not be called.

The problem is that when weakf.o is inside the static library, for some reason the linker cannot find this function, and the address of the function always ends as NULL. A static library is created using ar: ar rcs weaklibrary weakf.o

Has anyone had similar problems?

+4
source share
1 answer

While I do not know the exact operation of weak characters, it seems that you get what you are asking for: if no one else forces the weak function () to be present, main () will not be either. This makes sense to me: if you are trying to write code that works with an object X, as well as without it, then you do not want your code to force X to be included in your assembly at all costs. It seems that the β€œweak” is intended to ask if something is present, and not to ask for something to be present. Perhaps you can force weak characters with "-u weakFunction" as the linker option in your case.

+3
source

Source: https://habr.com/ru/post/1306769/


All Articles