undefined reference to `getline' in c

匿名 (未验证) 提交于 2019-12-03 02:23:02

问题:

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

#include  #include  #include   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

回答1:

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 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.



回答2:

getline isn't a standard function, you need to set a feature test macro to use it, according to my man page,

_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700 

for glibc 2.10 or later,

_GNU_SOURCE 

before that.



回答3:

I am also using MinGW. I checked MinGW headers and getline() does not appear in any C header, it appears only in C++ headers. This means the C function getline() does not exist in MinGW.



回答4:

For me compilator says

getline.cpp: In function ‘int main(int, char*)’: getline.cpp:15:52: error: cannot convert ‘int’ to ‘size_t* {aka long unsigned int*}’ for argument ‘2’ to ‘__ssize_t getline(char**, size_t*, FILE*)’

Check your compiler, linker, your folder with library. Maybe reinstall?


Write your own readline function. It's simple. Read char by char until you get new line



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!