如何正确使用“弱”?或C函数覆盖

Ala*_*Jay 7 c gcc

我想__attribute__((weak))正确使用功能覆盖。

我的代码无法正常工作。它出什么问题了?


普通

#include <stdio.h>

int __attribute__((weak)) doJob1(void);
int __attribute__((weak)) doJob2(int, int);

typedef int (*Job1)(void);
typedef int (*Job2)(int, int);
Run Code Online (Sandbox Code Playgroud)

普通

#include <stdio.h>
#include "common.h"

__attribute__((weak)) int doJob1(void)
{
        printf("doJob1 common WEAK\n");
        return 0;
}

__attribute__((weak)) int doJob2(int a, int b)
{
        printf("doJob2 common WEAK\n");
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

驱动程序

#include <stdio.h>
#include "common.h"

int doJob1(void)
{
        printf("doJob1 driverA Strong\n");
}

void main()
{
        Job1 j1 = doJob1;
        Job2 j2 = doJob2;

        j1();
        j2(0, 0);
}
Run Code Online (Sandbox Code Playgroud)

运行程序时,我看到:

sh> ./a.out
doJob1 common WEAK
doJob2 common WEAK
Run Code Online (Sandbox Code Playgroud)

我期望这个结果,而不是:

sh> ./a.out
doJob1 driverA Strong
doJob2 common WEAK
Run Code Online (Sandbox Code Playgroud)

如何获得预期的结果?

总体上,有许多功能,形式为“ Job1”,“ Job2” ...“ JobXX”。driverA希望将其自己的功能用于少量作业,而将公共功能用于某些作业,并且某些功能将为NULL:

ex> 
Job1 - driverA_Job1
Job2 - common Job2
Job3 - NULL
..
Run Code Online (Sandbox Code Playgroud)

不同的驱动程序(例如driverB)可能会做出不同的选择:

Job1 - common job1
job2 - B's own job2
job5 - NULL
Run Code Online (Sandbox Code Playgroud)

如何正确覆盖功能?

abe*_*nky 4

发生这种情况是因为头文件__attribute__((weak))中的声明common.h适用于两个定义;一个common.c(你想要变弱的)以及一个定义driverA.c(你想要变强的)。

要获得所需的行为,请__attribute__((weak)) 在 中应用common.c,而不是在头文件中。