简体   繁体   English

gcc在编译过程中错误“冲突类型”和“先前声明”

[英]gcc errors “conflicting types for” and “previous declaration of” during compiling

I am getting these errors despite declaring the "getline" and "copy" function prototypes before main(). 尽管在main()之前声明了“ getline”和“ copy”函数原型,但我还是遇到了这些错误。 This program comes straight from the code in The C Programming Language so I'm unsure what the issue is and how to fix it. 该程序直接来自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;
}

The exact errors produced by the compiler are: 编译器产生的确切错误是:

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__);
 ^~~~~~~

The POSIX function getline() is now a standard library function which is (already) declared in <stdio.h> (but wasn't standard when K&R was written). POSIX函数getline()现在是一个标准库函数,已在<stdio.h>声明(但在编写K&R时不是标准的)。 Hence, you cannot re-declare the function a little differently in C language. 因此,您不能在C语言中重新声明该函数。 A workaround is to rename your getline function to something else, eg getline_new The updated code is as below with this workaround, or you may want to switch to C++ that gives flexibility to have many functions with same name, but different arguments, including argument type (polymorphism concept) 一种解决方法是将您的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;
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM