ckernighan-and-ritchie

Why do I get this error: Conflicting types for getline


Can somebody please take a look at this and tell me what is wrong. I have 3 errors:

  1. error: Conflicting types for getline
  2. error: too few arguments to function call, expected 3 have 2
  3. error: conflicting types for getline.

I'm sure I have overlooked something simple but I cannot find my error. Thank you, here is the code:

#include <stdio.h>

#define MAXLINE 1000

int getline(char line[], int maxline); /* conflicting types for getline */
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) /* too few arguments to call, expected 3 have 2 */
        if (len > max) {
            max = len;          
            copy(longest, line);
        }   
    
    if (max > 0)
        //printf("longest line = %d characters\n -->", max);
        printf("%s", longest);

    return 0;
}

int getline(char s[], int lim) { /*conflicting types for getline*/

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

Solution

  • There's GNU function getline with the same, which is not part of C standard. Presumably, you are compiling with no -std (a specific C standard) specified that makes exposes this function's GNU declaration from <stdio.h>.

    You could compile with -std=c99 or -std=c11 like:

    gcc -Wall -Wextra -std=c11 gl.c
    

    or rename your function to something like my_getline() to avoid this conflict.

    Also, main()'s signature needs to be one of the standard ones. Since, you don't use commandline arguments, you can use:

    int main(void) { .. }
    

    See: What should main() return in C and C++?