函数指针 IAR (typedef void)

Function pointer IAR ( typedef void )

我正在使用 IAR 开发 STM8S Workbench。

我的代码

typedef     void    (*MyFunction)(); 

我遇到了这些错误:

Error[Pe513]: a value of type "void (*)(u8)" cannot be assigned to an entity of type "MyFunction"

我在网上搜索并找到了一个 AVR 示例,如下所示:

typedef void (*MyFunction)(void); 

同样不行。

任何修复它的想法。

对于可分配的指针,它们需要指向兼容的类型(并且左侧指向的类型需要具有右侧指向的类型的所有限定符)。参见 6.5.16.1p1

假设 u8uint8_t 又名 unsigned charvoid ()void (u8) 不兼容。

6.7.6.3p15(强调):

For two function types to be compatible, both shall specify compatible return types.146) Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types. If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions. If one type has a parameter type list and the other type is specified by a function definition that contains a (possibly empty) identifier list, both shall agree in the number of parameters, and the type of each prototype parameter shall be compatible with the type that results from the application of the default argument promotions to the type of the corresponding identifier. (In the determination of type compatibility and of a composite type, each parameter declared with function or array type is taken as having the adjusted type and each parameter declared with qualified type is taken as having the unqualified version of its declared type.)

不兼容是因为促销部分。字符类型被提升为 int 所以你可以这样做:

(void(*)()){0}=(void(*)(int)){0};
(void(*)(int)){0}=(void(*)()){0};

不允许对 u8 做同样的事情 / unsigned char:

(void(*)()){0}=(void(*)(unsigned char)){0}; //error
(void(*)(unsigned char)){0}=(void(*)()){0}; //error 

您需要使 typedef 完全等于 void (*)(u8) 或者您需要将目标函数的签名更改为 void (int)(或 void (unsigned))或者您需要强制转换函数指针。 (请注意,函数指针可以自由相互转换,但您需要在调用函数之前转换为正确的类型)。