采用 #pragma weak name 形式时,指令使 name 成为弱符号。链接程序没有找到 name 的符号定义时,不会显示错误消息,也不会出现符号的多个弱定义的错误消息。链接程序仅执行第一个遇到的定义。
如果另一个编译单元有函数或变量的强定义,那么 name 将链接到它。如果没有 name 的强定义,那么链接程序符号的值为 0。
Example1
编译单元A cu1.c
#include <stdio.h> extern int foo; #pragma weak foo int main() { int *ptr; ptr = &foo; if (ptr == 0) { printf("foo has not been defined "); } else { printf("foo was already defined as %d ", foo); } }
编译单元B cu2.c
int foo = 1;
只编译单元A:gcc cu1.c && ./a.out ,执行if语句。
编译两个单元:gcc cu1.c cu2.c && ./a.out ,执行else语句。
Example2
cu3.c
#include <stdio.h> extern void foo(void); #pragma weak foo int main() { if (foo != NULL) { foo(); } else { printf("foo has not been defined "); } }
编译 gcc cu3.c && ./a.out ,提示foo未被定义。
Example3
编译单元A cu4.c
#include <stdio.h> extern void foo(void); void foo1(void) { printf("Just in function foo1() "); } #pragma weak foo = foo1 int main() { foo(); }
编译单元B cu5.c
#include <stdio.h> void foo(void) { printf("In function foo() "); }
只编译单元A:gcc cu4.c && ./a.out ,执行foo1。
编译两个单元:gcc cu4.c cu5.c && ./a.out ,执行foo。