#pragma weak

采用 #pragma weak name 形式时,指令使 name 成为弱符号。链接程序没有找到 name 的符号定义时,不会显示错误消息,也不会出现符号的多个弱定义的错误消息。链接程序仅执行第一个遇到的定义。

如果另一个编译单元有函数或变量的强定义,那么 name 将链接到它。如果没有 name 的强定义,服务器空间,那么链接程序符号的值为 0。

Example1

编译单元A cu1.c

#include <stdio.h>extern int foo;#pragma weak fooint main() { int *ptr; ptr = &foo; if (ptr == 0) {printf(); } else {printf(, 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 fooint main() { if (foo != NULL) {foo(); } else {printf(); }}

编译 gcc cu3.c && ./a.out ,网站空间,服务器空间,提示foo未被定义。

Example3

编译单元A cu4.c

#include <stdio.h>extern void foo(void);void foo1(void) { printf();}#pragma weak foo = foo1int main() { foo();}

编译单元B cu5.c

#include <stdio.h>void foo(void) { printf();}

只编译单元A:gcc cu4.c && ./a.out ,执行foo1。

编译两个单元:gcc cu4.c cu5.c && ./a.out ,执行foo。

而做人的能力则会给你一百种机会。

#pragma weak

相关文章:

你感兴趣的文章:

标签云: