Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

different implementations for the same function (c/c++)

Tags:

c++

c

is it possible to have 2 (or more) different implementations for the same function declared in a header file? I'll give an example - let's say we have a header file called common.h and 2 source files called src1.c and src2.c.

common.h

//lots of common function declarations implemented in some file common.c 
int func(int a, int b);

src1.c

#include "common.h"

int func(int a, int b)
{
    return a+b;
}

src2.c

#include "common.h"

int func(int a, int b)
{
    return a*b;
}

let's say that I want each of the source file to use its local version of func(). is it possible to do so?

like image 605
noamgot Avatar asked Dec 19 '25 06:12

noamgot


2 Answers

Yes, but if you attempted to link your main program against both src1 and src2 you would encounter an error because it wouldn't know which definition to use.
Headers are just ways for other code objects to be aware of what's available in other objects. Think of headers as a contract. Contracts are expected to be filled exactly one time, not zero or multiple times. If you link against both src1 and src2, you've essentially filled the int func(int a, int b); contract twice.

If you need to alternate between two functions with the same signature, you can use function pointers.

like image 95
Mr. Llama Avatar answered Dec 21 '25 18:12

Mr. Llama


If you want each source file to only use its local implementation of func, and no other module uses those functions, you can remove the declaration from the header and declare them as static.

src1.c

static int func(int a, int b)
{
    return a+b;
}

src2.c

static int func(int a, int b)
{
    return a*b;
}

By doing this, each of these functions is only visible in the module it is defined in.

EDIT:

If you want two or more functions to implement an interface, you need to give them different names but you can use a function pointer to choose the one you want.

common.h

typedef int (*ftype)(int, int);
int func_add(int a, int b);
int func_mult(int a, int b);

src1.c

#include "common.h"

int func_add(int a, int b)
{
    return a+b;
}

src2.c

#include "common.h"

int func_mult(int a, int b)
{
    return a*b;
}

Then you can chose one or the other:

ftype func;
if (op=='+') {
    func = func_add;
} else if (op=='*') {
    func = func_mult;
...
}

int result = func(value1,value2);
like image 43
dbush Avatar answered Dec 21 '25 20:12

dbush



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!