Monday, December 23, 2013

Strong/Weak function

GCC中有一個很好用的feature... strong/weak link

__attribute__((weak))

於C code中,可以先define一個function,其function型態為weak,如此可以library方式release出去。
若第三方要修改此function,他方可以重複定義此function,於連結時第三方function取代原有default的function。

example...

/Working # cat CodeBase.c
#include 

void __attribute__((weak)) f()
{
printf("This is the original function\n");
}

int main(void)
{
f();
return 0;
}

/Working # gcc CodeBase.c -o CodeBase
/Working # ./CodeBase
This is the original function
/Working # cat CodeOverride.c
#include 
void f(void)
{
printf("This is override function\n");
}

/Working # gcc -c CodeBase.c CodeOverride.c
/Working # nm *.o

CodeBase.o:
00000000 W f
0000001c T main
U puts

CodeOverride.o:
00000000 T f
U puts
/Working # gcc -o CodeBase CodeBase.o CodeOverride.o
/Working # ./CodeBase
This is override function
/Working #

No comments:

Post a Comment