how to start a function using a Struct?

1637 views c

So I have to read a binary file full of structs like this :

typedef struct {
    char name[50];
    int a,b,c;
    int no_args;
} func;

In a imported header file are functions like:

void add(int,int);
void min(int,int);
void doSomething();

now the function name will always be like add / min / doSomething ... and the arguments of add are (a,b) of min are (b,c).

So how would I be able to start these functions, a map maybe to a function ? I want to do this so I kan benchmark my functions using the same large binary file. How would I go about doing this in C ? This is a simple version of my program.

func f = {"add",5,8,9,0};

now I need to start the function add(a,b) ;

Thx for reading

answered question

What do you mean "start the function"? If you want to invoke it, use add(42, -3);

When you compile a C program, add as a declared function name is handled by the compiler in a symbol table. The compiled binary code knows nothing about the function actually being called by the string "add". Conversely, you can't take a string in C and convert it to the address that the linker has assigned to the original token, add. What you can do is declare a function type inside a struct and then directly assign add to it.

Possible duplicate of How do I store a function to a variable? The linked question says C++, but the answer provided includes C.

1 Answer


I need to start the function add(a,b) ;

You probably mean that "you need to call the function add".

At runtime, the name of functions don't matter anymore (and conceptually do not exist). There is even a Unix utility, called strip, to remove every name (and all the symbol tables) inside an executable.

So you could do the following: construct a data structure associating names (e.g. strings like add) to function pointers. For instance, you might first define a type for the signature of add and sub:

typedef int sig2t (int, int);

Then, fill an array with both names and function pointers; first declare its type:

struct funbind_st {
  const char*fname;
  sig2t* faddr;

And the array:

const struct funbind_st funbindings[] = {
 { "add", add },
 { "sub", sub },
 { NULL, (sig2t*)0 }

Then, finding in that funbindings the element of fname the "sub" string is a simple exercise (you'll need strcmp to compare strings).

posted this

Have an answer?


Please login first before posting an answer.