目录
一、C语言弱函数定义(weak关键字)
1、weak关键字简介
2、weak关键字使用示例
二、总结
一、C语言弱函数定义(weak关键字)
1、weak关键字简介
使用 __attribute__((weak)) 修饰函数,告诉编译器此函数为同名函数的备选,如果定义了其他同名函数,让编译器优先使用其他同名函数,如果未定义其他同名函数,那么就使用此函数。
2、weak关键字使用示例
创建两个源文件 main.c test.c。
main.c代码如下:
#include <stdio.h>
void test_func(void);
int main()
{
test_func();
return 0;
}
__attribute__((weak)) void test_func(void)
{
printf("test_func\r\n");
}
test.c代码如下:
#include <stdio.h>
void test_func(void)
{
printf("test_func1\r\n");
}
代码说明:main.c中定义弱函数test_func,test.c中定义同名函数test_func,在main函数中调用test_func()。
编译代码,编译命令:gcc main.c test.c。
程序执行结果如下图:
根据结果可以发现,程序输出的结果是字符串"test_func1",所以在main函数中实际调用的是test.c中的 test_func函数。说明test.c中的test_func函数覆盖了同名弱函数。
二、总结
weak修饰函数一般用来系统默认实现,如果用户需要自定义,那么只需要重写同名函数即可覆盖系统的默认实现。类似于C++语言的方法重写。