Raulp
Raulp

Reputation: 8186

Calling a C function at Runtime from a file among many files having same function signature

I have four files f1,f2,f3 and f4 with same function names and signature but different implementation.

f1 : 
func1(int par1,int par2)

f2 : 
func1(int par1,int par2)


f3 : 
func1(int par1,int par2)

f4 : 
func1(int par1,int par2)

now each function will be called depending on some version ID , for example if version ID is 1 i will call func1 of file 1 if it is 2 I will call func1 of file 2 .How can I implement it !

I tried creating another function argument as version ID but then I have to change all the function signature which is not acceptable.This has to be done in C .Had it been in C++ i could have created a class and could have put each file content in a new class and then created the instance of each class but its pure C.

Or is there any #Pragma for the same!

Any inputs !

Upvotes: 0

Views: 130

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409404

Since you don't have any operating system, the only way I could think about would be if you compiled and linked each file separately, and put them separately in the ROM image as well. Then extract the addresses from the ROM image, and use that address in a table (or something) and use for calling.


Just thought of another way, and that would be to make the functions static. Then have a unique function to get a function-pointer structure that you can use. This is a very common way to handle drivers.

Upvotes: 4

Jerry Coffin
Jerry Coffin

Reputation: 490468

You really have two separate problems to deal with here.

First is the fact that the functions all have the same name, so you have no way of referring to any one of them unambiguously. To fix that, you almost certainly want to rename them to func1, func2, func3, etc.

Then you have to get from an input of 1 to calling func2, an input of 2 to calling func2, and so on. Fortunately, that's pretty easy to manage:

// the type of a pointer to one of the functions:
typedef void func(int par1, int par2);

// an array of pointers to the functions:
func funcs[] = {func1, func2, func3, func4};

// call the correct function from the array, based on the ID:
funcs[ID]();

Upvotes: 5

Related Questions