c 中对“getline"的未定义引用 [英] undefined reference to `getline' in c
问题描述
我正在学习在 C 编程中使用 getline,并尝试了来自 http://crasseux 的代码.com/books/ctutorial/getline.html
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;
}
然而,问题是编译器不断返回以下错误:未定义对'getline'的引用.你能告诉我是什么问题吗?谢谢!
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!
我使用的是 Win7 64 位 + Eclipse Indigo + MinGW
I am using Win7 64bit + Eclipse Indigo + MinGW
推荐答案
其他答案已经涵盖了大部分内容,但存在几个问题.首先,getline()
不在 C 标准库中,但它是 POSIX 2008 的扩展.通常,它可用于兼容 POSIX 的编译器,因为宏 _POSIX_C_SOURCE 将使用适当的值定义.在 getline()
标准化之前,您可能有一个较旧的编译器,在这种情况下,这是一个 GNU 扩展,并且您必须在 #include < 之前
以启用它,并且必须使用与 GNU 兼容的编译器,例如 gcc.#define _GNU_SOURCE
;stdio.h>
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.
此外,nbytes
的类型应该为 size_t
,而不是 int
.至少在我的系统上,这些大小不同,size_t
更长,使用 int*
而不是 size_t*
可以有严重的后果(并且也不能使用默认的 gcc 设置进行编译).有关详细信息,请参阅 getline 手册页 (http://linux.die.net/man/3/getline).
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.
这篇关于c 中对“getline"的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!