strong.c
#include <stdio.h>
int weak_fun(int args)
{
printf("args=%d, %s, %s\n",args, __FILE__,__FUNCTION__);
return 0;
}
weak.c
#include <stdio.h>
static int __def_weak_fun(int args)
{
printf("args= %d, %s, %s\n",args,__FILE__,__FUNCTION__);
return -1;
}
int weak_fun(int errno) __attribute__((weak, alias("__def_weak_fun")));//注释这行,打开下面两条注释
//int weak_fun(int errno) __attribute__ ((weak));
int main(int argc, char **argv)
{
// asm(".weak weak_fun\n\t .set weak_fun, __def_weak_fun\n\t");
if(weak_fun)
weak_fun(1000);
return 0;
}
$ gcc -o aa weak.c
$./aa
args= 1000, weak.c, __def_weak_fun
$gcc -o aa weak.c strong.c
$./aa
args=1000, strong.c, weak_fun
(1)asm(".weak weak_fun\n\t .set weak_fun, __def_weak_fun\n\t");
与 void weak_fun __attribute__ ((weak,alias("__def_weak_fun")));等效。
(2)给函数加上weak属性时,即使函数没定义,函数被调用也可以编译成功。(3)当有两个函数同名时,则使用强符号(也叫全局符号,即没有加weak的函数)来代替弱符号(加weak的函数)。
(4)当函数没有定义,但如果是“某个函数”的别名时,如果该函数被调用,就间接调用“某个函数”。