I have been struggling with function pointers for some time now. Maybe you guys can help me out.
In my project I have multiple functionalities for the same device and each functionality is written in its own .c file. The generic functionalities (which apply to all device functions) are written in generic.c.
I would like to create a function pointer array in the generic c file and fill that array in the other function files. So I can call the right function based on a device function identifier in the generic file.
What I have right now:
// in generic.h:
typedef void (*func_ptr_t[])(arguments);
extern func_ptr_t devFunctions[3];
And I would like to:
// in function1.c:
#include "generic.h"
devFunctions[1] = &functionName;
But then it complains about a type specifier missing AND the array initializer must be a list. If I add the type like
func_ptr_t devFunctions[1] = &functionName;
I get an error about an incomplete element type 'func_ptr_t'.
I can't initialize the entire array list from one file since it is filled from multiple files.
Anybody got an idea on how to tackle this?
Thanks!
-edit-
Because you can't use statements outside of functions I've changed my application. Now it does not use an array anymore and it updates the function pointer in the generic.c upon calling the specific function file.
So the end result:
In generic.h:
typedef void (*func_ptr_t)(<function arguments>)
In generic.c:
func_ptr_t devFunction;
In function1.c:
#include "generic.h"
extern func_ptr_t devFunction;
void functionToBeCalledFromMain( void ){
devFunction = functionName;
}
void functionName (void ){
// Function to be called from generic.c via function pointer
}
For an example about functions of the type int f(int);
, you can check :
/* function definition */
int functionName(int arg)
{
/* do things */
return arg * 2;
}
/* create the type "function pointer int->int" */
typedef int (*func_ptr_t)(int);
/* create the array */
func_ptr_t devFunctions[3];
int main(void)
{
/* associate the good function */
devFunctions[0] = &functionName;
/* call it with an arg */
return devFunctions[0](42);
}