这是我试图直接从“C编程语言”的1.9节中运行的程序。
#include <stdio.h>
#define MAXLINE 1000
int getline(char line[], int maxline);
void copy(char to[], char from[]);
main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max = 0;
while ((len = getline(line, MAXLINE)) > 0)
if (len > max) {
max = len;
copy(longest, line);
}
if (max > 0)
printf("%s", longest);
return 0;
}
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;
}以下是我尝试使用Ubuntu 11.10编译程序时得到的错误:
cc word.c -o word
word.c:4:5: error: conflicting types for ‘getline’
/usr/include/stdio.h:671:20: note: previous declaration of ‘getline’ was here
word.c:26:5: error: conflicting types for ‘getline’
/usr/include/stdio.h:671:20: note: previous declaration of ‘getline’ was here
make: *** [word] Error 1为了确保这本书中的印刷没有问题,我引用了本书(http://users.powernet.co.uk/eton/kandr2/krx1.html)中章后练习的这组答案,当我试图从该链接运行练习18、19、20、21等时,我得到了类似的错误。当我不能运行程序来查看它们的输出时,这真的很难学习。此问题是在一个程序中引入字符数组和函数调用时出现的。如果你对这个问题有任何建议,我将不胜感激。
发布于 2012-01-07 03:09:25
问题是getline()是一个标准库函数。(在stdio.h中定义)您的函数具有相同的名称,因此与其冲突。
解决方案是简单地更改名称。
发布于 2013-06-29 16:53:07
冲突函数getline()是一个GNU/POSIX扩展。
K&R声明他们在他们的书(c.f.)中专门讨论了ANSI,它没有提供这个功能。
作者介绍了
标准C语言编程的完整指南。
为了将gcc设置为"K&R兼容模式“,您可以指定编译的ANSI或ISO模式。它们旨在禁用扩展,例如函数getline()。这最终可能会消除编辑K&R提供的其他示例的需要。
例如,下面的编译就很好:
$ gcc test.c -ansi
$ gcc test.c -std=c89(除了他们抱怨带有-Wall的main()的隐式默认返回类型。)
显然,在某些系统上,这些模式可能不会像这里介绍的那样工作(apparently some version(s) of Mac OS fail to correctly disable all extensions)。我在我的机器上成功地进行了测试:
$ gcc --version
gcc (GCC) 4.7.2 20121109 (Red Hat 4.7.2-8)
Copyright (C) 2012 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.发布于 2012-01-07 03:10:56
这是因为stdio.h有一个getline()函数。
因此,实现此功能的简单方法是将函数重命名为my_getline()
getline()和getdelim()最初都是GNU扩展。它们在POSIX.1-2008中是标准化的。
https://stackoverflow.com/questions/8763052
复制相似问题