编译过程中"conflicting types for"和"previous declaration of" 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] = '';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '')
++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:mingwincludestdio.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:mingwincludestdio.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] = '';
return i;
}
void copy(char to[], char from[])
{
int i;
i = 0;
while ((to[i] = from[i]) != '')
++i;
}

相关内容

最新更新