4

除了为函数声明函数指针 typedef 之外,是否可以从函数声明中获取它?

通常,

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

我想要的是:

int foo(int x);
foo* aFunc;

我想将它用于 dlsym:

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

如果我更新 foo 却忘记更新 fooFunc,反之亦然,那将很糟糕。另外,我可能有很多函数,维护函数声明和与这些函数关联的函数指针类型定义会更费力。

结论:AndreyT 的答案是最便携的,但如果您为 gcc 编写代码,那么 typeof 是一个很好的解决方案。

4

5 回答 5

6

如果您专门讨论声明,即函数的非定义声明,您可以通过为函数类型定义 typedef-name 并在两种情况下使用它来消除冗余 - 声明函数本身并声明指针对它,像这样

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

即 typedef-names 可用于非定义函数声明。但是,您不能在函数定义中使用 typedef 名称,这意味着稍后您仍然需要这样做

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

这基本上使上述技巧几乎无用。

当然,如果这是您的情况,这并不能帮助您从现有的不可修改函数声明生成指针。

于 2009-11-04T17:12:03.780 回答
5

如果你有 gcc,typeof可以工作。

更新

$ 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:警告:未使用的参数“argv”
$ ./fxf
main() 调用。
main() 调用。
于 2009-11-04T17:03:29.983 回答
2

简单的回答:不,那行不通。foo是具有原型 ( ) 的特定int (int)函数。以foo您所做的方式使用有点像使用 anint来声明另一个int

4 x; // expect this to be the same as int x

也就是说,可能有编译器扩展可以使它工作。我知道即将到来的 C++ 标准将具有decltype允许这样做的关键字。使用它,以下可能有效(未经测试,因为我手边没有支持的编译器):

int foo(int x);

decltype(&foo) aFunc = dlsym(lib, "foo");
于 2009-11-04T16:49:29.473 回答
0

It is not possible. However, you can write some code that would generate a warning, so that you would catch type mismatch. The following code generates an assignment from incompatible pointer type warning.

#include <stdio.h>

int foo(int, int);
typedef  int(*fooFunc)(int);

fooFunc myfunc;

int foo(int x, int y)
{
    return 2*x + y;
}

int main(int argc, char **argv)
{
    myfunc = foo;
    printf("myfunc : 0x%x\n", (unsigned int)myfunc);
    return 0;
}

Of course, this means you would have to write this test code where the foo function is visible, so this is still more code to add for each function type. The solution here is probably a code generator, that would generate a proper header file containing both functions and their associated typedefs

于 2009-11-04T17:19:57.540 回答
0

不完全相同,但您可以对函数进行 typedef 并将其用于原型和指针。

typedef int fooFunc(int);
fooFunc foo;
fooFunc *aFunc;
于 2009-11-04T17:38:37.597 回答