可以在函数定义中使用函数原型typedef吗?

时间:2011-01-01 17:45:46

标签: c typedef function-declaration

我有一系列具有相同原型的功能,比如说

int func1(int a, int b) {
  // ...
}
int func2(int a, int b) {
  // ...
}
// ...

现在,我想简化他们的定义和声明。当然我可以使用这样的宏:

#define SP_FUNC(name) int name(int a, int b)

但是我想把它保存在C中,所以我尝试使用存储说明符typedef

typedef int SpFunc(int a, int b);

这似乎适用于声明:

SpFunc func1; // compiles

但不是定义:

SpFunc func1 {
  // ...
}

这给了我以下错误:

error: expected '=', ',', ';', 'asm' or '__attribute__' before '{' token

有没有办法正确地做到这一点还是不可能? 根据我对C的理解,这应该有效,但事实并非如此。为什么呢?


注意,gcc理解我要做的事情,因为,如果我写

SpFunc func1 = { /* ... */ }
它告诉我

error: function 'func1' is initialized like a variable

这意味着gcc理解SpFunc是一种函数类型。

2 个答案:

答案 0 :(得分:43)

您无法使用typedef为函数类型定义函数。它被明确禁止 - 参考6.9.1 / 2和相关的脚注:

  

在函数定义中声明的标识符(函数的名称)应该是   有一个函数类型,由函数定义的声明部分指定。

     

意图是函数定义中的类型类别不能从typedef继承:

typedef int F(void); // type F is "function with no parameters
                     // returning int"
F f, g; // f and g both have type compatible with F
F f { /* ... */ } // WRONG: syntax/constraint error
F g() { /* ... */ } // WRONG: declares that g returns a function
int f(void) { /* ... */ } // RIGHT: f has type compatible with F
int g() { /* ... */ } // RIGHT: g has type compatible with F
F *e(void) { /* ... */ } // e returns a pointer to a function
F *((e))(void) { /* ... */ } // same: parentheses irrelevant
int (*fp)(void); // fp points to a function that has type F
F *Fp; //Fp points to a function that has type F

答案 1 :(得分:0)

typedef定义类型,而不是标题(源代码文本)。如果你需要分解标题的代码,你必须使用#define(虽然我不推荐它)。

([编辑]第一个工作的原因是它没有定义原型 - 它定义了typedef定义的类型的变量,这不是你想要的。)

相关问题