The
weak
attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions which can be overridden in user code, though it can also be used with non-function declarations.libweak.c
#include <stdio.h> void weakfunc() __attribute__((weak)); void weakfunc() { printf ("default weak function\n"); }main.c
#include <stdio.h> void weakfunc() { printf ("weak function from main\n"); } int main () { weakfunc(); return 0; }Compile the library and main function.
#gcc -shared -o libweak.so weakfunc.c #gcc -o weakfunc{,.c} -lweak -L. #LD_LIBRARY_PATH=. ./main weak function from mainFrom above, it is very clear that the weak function of the library is replaced.
#objdump -t libweak.so |grep weakfunc 0000046c w F .text 00000014 weakfuncIn the library, this function has weak attribute.
#objdump -t main |grep weakfunc 080484e4 g F .text 00000014 weakfuncHowever, this function is presented as global attribute.
沒有留言:
張貼留言