簡體   English   中英

gcc在編譯過程中錯誤“沖突類型”和“先前聲明”

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

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

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;
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM