为什么使用 typedef 函数是错误的?

Why is this usage of typedef-ed function an error?

我有以下代码:

#include <stdio.h>

typedef void (*myfunc_t)(int x);

myfunc_t myfunc(int x)
{
    printf("x = %d\n", x);

    return;
}

int main(void)
{
    myfunc_t pfunc = myfunc;

    (pfunc)(1);

    return 0;
}

为 C99、标准 C 编译时,出现错误:

prog.c: In function ‘myfunc’:
prog.c:9:6: error: ‘return’ with no value, in function returning non-void [-Werror]
      return;
      ^~~~~~
prog.c:5:14: note: declared here
     myfunc_t myfunc(int x)
              ^~~~~~
prog.c: In function ‘main’:
prog.c:14:26: error: initialization of ‘myfunc_t’ {aka ‘void (*)(int)’} from incompatible pointer type ‘void (* (*)(int))(int)’ [-Werror=incompatible-pointer-types]
         myfunc_t pfunc = myfunc;
                          ^~~~~~

SO 中的一些问题已经解释了 myfunc_t 的 return 类型是 void(例如,)。那么,为什么会出现这些错误?

请注意,如果我将 myfunc 的类型从 myfunc_t 更改为 void,则程序构建正常。

myfunc_t myfunc(int x)

此语句创建了一个函数 myfunc,它 return 是一个函数指针 myfunc_t

但是在函数定义中你没有 returning 任何东西。此外,这样做会使 myfuncmyfunc_t 类型不兼容(return 值不同)

你需要的是将函数声明和定义为

void myfunc(int x) 
{
     ...
}