在 C语言中,可以通过使用__attribute__((weak))方式或#pragma weak方式来声明弱函数,当函数未实现时编译不报错。
/*************************************************************************
> File Name: t3.c
> Author: 麦子邪
> Mail: noevil@gmail.com
> Created Time: Fri 29 Mar 2024 09:44:03 AM UTC
************************************************************************/
#include <stdio.h>
#include <unistd.h>
//弱声明方式1.1
//void test_fun (void) __attribute__((weak));
//弱声明方式1.2
//__attribute__((weak)) void test_fun (void) ;
//弱声明方式1.3
void __attribute__((weak)) test_fun (void) ;
//弱声明方式2
#pragma weak func2
void func2(int value);
#if 0
void func2(int value)
{
printf("func2 is test, %d\n", value);
}
#endif
#if 0
void test_fun (void)
{
int cnt = 0;
while(1)
{
sleep(1);
printf("%s cnt:%d \n", __func__, cnt++);
}
}
#endif
int main()
{
if (func2) func2(10);
if (test_fun) test_fun();
return 0;
}
上面代码示例了两种弱声明的方式,不管哪种,在实际调用时,都应该像man函数中那样,先判断函数指针是否有效,然后再调用。