c - K&R函数声明

标签 c function gcc

C 专家我正在尝试学习 C,我的 hp-ux 上的编译器使用 K & R

我一直有

  1. 第 32 行:错误 1584:类型声明不一致:“用法”
  2. 第 33 行:错误 1705:函数原型(prototype)是 ANSI 功能
  3. 警告 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/

相关文章:

c - 我的循环队列实现无法正常工作

c - 在 POSIX 中执行线程

perl - 阶乘递归达到零时出错

c++ - 在 GCC 中添加到父目录的包含路径

c - C 中的 log (1-var) 操作

c - 使用 epoll_create1() 而不是 epoll_create() 有什么好处

ios - 为什么指针无法取回新值? iOS

Javascript 将 Promise 推送到数组中

编译时函数 ptr 取消引用

c - 如何让 GCC 不生成 .h.gch 文件