当我试图编译代码时,我收到了如下所示的错误
main.c:12:15:错误:"ascii_to_hex"的类型冲突无符号字符ascii_to_hex(无符号字符*buf(
#include <stdio.h>
#include <stdlib.h>
int main()
{
unsigned char str[] = {0x32, 0x35, 0x34, 0x035};
ascii_to_hex(str);
return 0;
}
unsigned char ascii_to_hex(unsigned char* buf)
{
unsigned char hundred, ten, unit, value;
hundred = (*buf-0x30)*100;
ten = (*(buf + 1)-0x30)*10;
unit = *(buf+2)-0x30;
value = (hundred + ten + unit);
printf("nValue: %#04x n", value);
return value;
}
我在这里做什么不对?
在声明ascii_to_hex
之前使用它,因此编译器推断它具有"默认";函数的签名。我忘了那到底是什么,[EDIT:它显然是
int ascii_to_hex()
--我查了一下],但不管是什么,它都不是
unsigned char ascii_to_hex(unsigned char* buf)
编译器告诉你的是,它推断出的函数签名与后来遇到的签名不匹配。这在gcc:的输出中非常清楚
cc program.c -o program
program.c: In function ‘main’:
program.c:11:1: warning: implicit declaration of function ‘ascii_to_hex’ [-Wimplicit-function-declaration]
11 | ascii_to_hex(str);
| ^~~~~~~~~~~~
program.c: At top level:
program.c:16:15: error: conflicting types for ‘ascii_to_hex’
16 | unsigned char ascii_to_hex(unsigned char* buf)
| ^~~~~~~~~~~~
program.c:11:1: note: previous implicit declaration of ‘ascii_to_hex’ was here
11 | ascii_to_hex(str);
| ^~~~~~~~~~~~
make: *** [<builtin>: program] Error 1
因此,您可能需要考虑使用更好的编译器或IDE,或者关闭开发管道中抑制大多数相关信息的任何部分。
要解决此问题,您需要将函数定义移动到main
的定义之上,或者为函数提供一个原型,以便编译器在调用时知道其签名。