Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c - Why do I get a "conflicting types for getline" error when compiling the longest line example in chapter 1 of K&R2?

Here is a program I'm trying to run straight from section 1.9 of "The C Programming Language".

#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 != '
'; ++i)
        s[i] = c;
    if (c == '
') {
        s[i] = c;
        ++i;
    }
    s[i] = '';
    return i;
}


void copy(char to[], char from[])
{
    int i;

    i = 0;
    while ((to[i] = from[i]) != '')
        ++i;
}

Here is the error I get when I try to compile the program using 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

Just to make sure it wasn't a problem with the print in the book, I referenced this set of answers to back of chapter exercises from the book (http://users.powernet.co.uk/eton/kandr2/krx1.html) and I get a similar error when I try to run exercises 18, 19, 20, 21, etc., from that link. It's really hard to learn when I can't run the programs to see how they output. This issue started when introducing character arrays and function calls in one program. I'd appreciate any advice on this issue.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that getline() is a standard library function. (defined in stdio.h) Your function has the same name and is thus clashing with it.

The solution is to simply change the name.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...