Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use "weak" correctly?? or C function overriding

Tags:

c

gcc

I want to use __attribute__((weak)) correctly, for function overriding.

My code does not work as I expected. What's wrong with it?


common.h

#include <stdio.h>

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

typedef int (*Job1)(void);
typedef int (*Job2)(int, int);

common.c

#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;
}

driverA.c

#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);
}

When I run the program, I see:

sh> ./a.out
doJob1 common WEAK
doJob2 common WEAK

I expected this result, instead:

sh> ./a.out
doJob1 driverA Strong
doJob2 common WEAK

How can I obtain the expected result?

Overall, there are many functions of the form "Job1", "Job2"..."JobXX". driverA wants to use its own functions for few jobs and common functions for for some jobs, and some functions will be NULL:

ex> 
Job1 - driverA_Job1
Job2 - common Job2
Job3 - NULL
..

A different driver, say driverB, may make different choices:

Job1 - common job1
job2 - B's own job2
job5 - NULL

How can I override functions correctly?

like image 455
AlanJay Avatar asked May 28 '19 11:05

AlanJay


1 Answers

This is happening because the __attribute__((weak)) declaration in the common.h header file applies to BOTH definitions; the one in common.c (which you intend to be weak) and also the definition in driverA.c (which you intend to be strong).

To get the behavior you want, apply the __attribute__((weak)) only in common.c, and not in the header file.

like image 195
abelenky Avatar answered Sep 21 '22 16:09

abelenky