首页 > 解决方案 > 编译期间 gcc 错误“冲突类型”和“先前声明”

问题描述

尽管在 main() 之前声明了“getline”和“copy”函数原型,但我收到了这些错误。这个程序直接来自C 编程语言中的代码,所以我不确定问题是什么以及如何解决它。

#include <stdio.h>

int getline(char line[], int maxline);
void copy(char to[], char from[]);

int main()
{

}

int getline(char s[], int lim)
{
    int c, i;

    for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
        s[i] = c;
    if (c == '\n') {
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

void copy(char to[], char from[])
{
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
}

编译器产生的确切错误是:

string_reverser.c:4:5: error: conflicting types for 'getline'
 int getline(char line[], int maxline);
     ^~~~~~~

In file included from string_reverser.c:1:0:
c:\mingw\include\stdio.h:650:1: note: previous declaration of 'getline' was here
 getline (char ** __restrict__, size_t * __restrict__, FILE * __restrict__);
 ^~~~~~~

string_reverser.c:27:5: error: conflicting types for 'getline'
 int getline(char s[], int lim)
     ^~~~~~~

In file included from string_reverser.c:1:0:
c:\mingw\include\stdio.h:650:1: note: previous declaration of 'getline' was here
 getline (char ** __restrict__, size_t * __restrict__, FILE * __restrict__);
 ^~~~~~~

标签: c

解决方案


POSIX 函数getline()现在是一个标准库函数,它(已经)在中声明<stdio.h>(但在编写 K&R 时不是标准的)。因此,您不能在 C 语言中以稍有不同的方式重新声明该函数。一种解决方法是将您的 getline 函数重命名为其他名称,例如 getline_new 使用此解决方法更新的代码如下所示,或者您可能希望切换到 C++,它可以灵活地拥有许多具有相同名称但不同参数的函数,包括参数类型(多态概念)

    #include <stdio.h>

    int getline_new(char line[], int maxline);
    void copy(char to[], char from[]);

    int main()
    {

    }

    int getline_new(char s[], int lim)
    {
       int c, i;

       for (i=0; i<lim-1 && (c=getchar())!=EOF && c!='\n'; ++i)
        s[i] = c;
       if (c == '\n') {
        s[i] = c;
        ++i;
     }
     s[i] = '\0';
     return i;
    }

   void copy(char to[], char from[])
   {
    int i;

    i = 0;
    while ((to[i] = from[i]) != '\0')
        ++i;
   }

推荐阅读