C 专家我正在尝试学习 C,我的 hp-ux 上的编译器使用 K & R
我一直有
- 第 32 行:错误 1584:类型声明不一致:“用法”
- 第 33 行:错误 1705:函数原型(prototype)是 ANSI 功能
- 警告 419:为数组 argv 分配了零长度存储
int main(c,v)
{
int result;
int errno;
int argc;
char *argv[];
if(argc < 3 || argc > 3) {
Usage(argv[0]);
exit(1);
}
system("clear");
result = Search_in_File(argv[1], argv[2]);
if(result == -1) {
perror("Error");
printf("Error number = %d\n", errno);
exit(1);
}
return(0);
}
void Usage(char *filename)
{
printf("Usage: %s <file> <string>\n", filename);
printf("%s version 1.0 \nCopyright(c) CodingUnit.com\n", filename);
}
提前感谢您的任何意见
最佳答案
天哪,HP-UX C 编译器仍然默认为 K&R?!这在 20 年前还可以原谅,但现在就不再那么情有可原了。
要将此编译为 K&R(ANSI 之前)C,请按如下方式更改函数定义:
int main( argc, argv )
int argc; /* move declaration of argc and argv from the */
char **argv; /* body of main to here */
{
/* leave everything else the same */
}
int Usage( filename ) /* void was introduced in C89, don't think it existed in K&R */
char *filename;
{
/* leave the same */
}
话虽如此,正确的答案是使用正确的函数原型(prototype)并找到将编译器置于 C90(或更高版本)模式的命令行选项,或者使用 gcc
。 没有人应该在新代码中使用 K&R 风格的函数定义。
编辑
请注意,在 K&R 和 C89/90 下,如果编译器在看到该函数的声明之前看到一个函数调用,它将假定该函数返回 int
。自从我声明 Usage
返回int
上面(因为 K&R 中没有 void
类型),此代码将在 K&R 下编译。
如果我定义了Usage
返回 int
以外的任何类型,编译器会提示隐含声明和函数定义之间的类型不匹配。
从 C99 开始,隐式 int
不再允许键入,因此所有函数在使用前必须显式声明或定义。
关于c - K&R函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43762148/