gcc之weak,alias属性

来源:互联网 发布:淘宝网旗舰店是正品吗 编辑:程序博客网 时间:2024/05/19 22:02

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


总结weak属性

(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)当函数没有定义,但如果是“某个函数”的别名时,如果该函数被调用,就间接调用“某个函数”。
0 0
原创粉丝点击