Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined reference to `getline' in c

I am learning to use getline in C programming and tried the codes from http://crasseux.com/books/ctutorial/getline.html

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int atgc, char *argv[])
{
    int bytes_read = 1;
    int nbytes = 10;
    char *my_string;

    my_string = (char *)malloc(nbytes+1);

    puts("Please enter a line of text");

    bytes_read = getline(&my_string, &nbytes, stdin);

    if (bytes_read == -1)
    {
        puts ("ERROR!");
    }
    else
    {
        puts ("You typed:");
        puts (my_string);
    }

    return 0;
 }

However, the problem is that the compiler keeps returning errors of this: undefined reference to 'getline'. Could you please tell me what the problem is? Thank you!

I am using Win7 64bit + Eclipse Indigo + MinGW

like image 362
Eric Cartman Avatar asked Oct 28 '12 20:10

Eric Cartman


People also ask

What does getline () do in C?

The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.

What library is Getline in C?

This file is part of the GNU C Library.

Does Getline work with C strings?

Reading strings: get and getlineThe functions get and getline (with the three parameters) will read and store a c-style string. The parameters: First parameter (str) is the char array where the data will be stored.

Does Getline work on Windows?

getline is a POSIX function, and Windows isn't POSIX, so it doesn't have some POSIX C functions available. You'll need to roll your own. Or use one that has already been written. Save this answer.


1 Answers

The other answers have covered most of this, but there are several problems. First, getline() is not in the C standard library, but is a POSIX 2008 extension. Normally, it will be available with a POSIX-compatible compiler, as the macros _POSIX_C_SOURCE will be defined with the appropriate values. You possibly have an older compiler from before getline() was standardized, in which case this is a GNU extension, and you must #define _GNU_SOURCE before #include <stdio.h> to enable it, and must be using a GNU-compatible compiler, such as gcc.

Additionally, nbytes should have type size_t, not int. On my system, at least, these are of different size, with size_t being longer, and using an int* instead of a size_t* can have grave consequences (and also doesn't compile with default gcc settings). See the getline manual page (http://linux.die.net/man/3/getline) for details.

With that change made, your program compiles and runs fine on my system.

like image 193
amaurea Avatar answered Oct 14 '22 02:10

amaurea