Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is There C Syntax For Function Pointer From Function Declaration

Instead of declaring a function pointer typedef for a function, is it possible to get it from the function declaration?

Typically,

int foo(int x);
typedef int (*fooFunc)(int);
fooFunc aFunc;

What I want:

int foo(int x);
foo* aFunc;

I want to use it for dlsym:

foo* aFunc;
aFunc = dlsym(lib, "foo");
aFunc(x);

If I update foo and forgot to update fooFunc, or vice versa, that would be bad. Also, I may have many functions and it would be more work to maintain both the function declarations and the function pointer typedefs that are associated with those functions.

Conclusion: AndreyT's answer is the most portable but if you code for gcc then typeof is a great solution.

like image 455
KlaxSmashing Avatar asked Dec 14 '22 01:12

KlaxSmashing


2 Answers

If you are talking about a declaration specifically, i.e. a non-defining declaration of a function, you can remove the redundancy by defining a typedef-name for function type and using it in both cases - to declare the function itself and to declare a pointer to it, like this

typedef int FuncType(int); /* <- function type */
FuncType foo; /* <- declaration of `int foo(int)` */
FuncType *aFunc; /* <- definition of `int (*aFunc)(int)` */

I.e. typedef-names can be used in non-defining function declarations. However, you can't use a typedef name in function definition, meaning that later you'll still have to do

int foo(int x) /* <- no way to use the above `FuncType` here */
{
  /* whatever */
}

which basically renders the above trick virtually useless.

Of course, this doesn't help you to generate a pointer from an existing non-modifiable function declaration, if that's your situation.

like image 175
AnT Avatar answered Apr 11 '23 18:04

AnT


If you have gcc, typeof works.

Update

$ cat fxf.c
#include <stdio.h>

int main(int argc, char **argv) {
  typedef __typeof__ (main) function_of_same_type_as_main_t;
  function_of_same_type_as_main_t *f;

  printf("main() called.\n");
  f = main;
  if (argc) f(0, NULL);
  return 0;
}
$ /usr/bin/gcc -std=c89 -pedantic -Wall -Wextra -o fxf fxf.c
fxf.c:3: warning: unused parameter ‘argv’
$ ./fxf
main() called.
main() called.
like image 42
pmg Avatar answered Apr 11 '23 19:04

pmg