c - 编译期间 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__);
^~~~~~~
解决方案
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;
}
推荐阅读
- java - 如何将 application.properties 传递给 dockerfile
- html - Windows 自动更新后 HTML 代码停止打开本地驱动器“.ods”
- r - 我如何计算,在一个会话中总共有多少个项目?
- python - 在 C 中为 Python 创建 C 扩展对象并将其作为参数传递
- flutter - Flutter Listview - 字幕和日期差异问题
- sql - 我正在尝试使用 SQL 邮件以 xlsx 格式发送查询结果,但在 excel 中,它在列和行之间没有得到适当的干扰
- javascript - 如何为我的图片库创建这种悬停效果?
- arrays - 在 C 中使用 char* arr 输入和读取超过 200 个字符的长数字
- google-cloud-run - 云调度程序的身份验证问题
- python-3.x - 使用 unittest.mock,如何根据实例属性模拟具有 return_value 的类属性?