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.
//lots of common function declarations implemented in some file common.c
int func(int a, int b);
#include "common.h"
int func(int a, int b)
{
return a+b;
}
#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?
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.
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.
static int func(int a, int b)
{
return a+b;
}
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.
typedef int (*ftype)(int, int);
int func_add(int a, int b);
int func_mult(int a, int b);
#include "common.h"
int func_add(int a, int b)
{
return a+b;
}
#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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With