在C中对`getline’的未定义引用

undefined reference to `getline' in c

我正在学习在C编程中使用getline,并尝试了http://crasseux.com/books/ctutorial/getline.html中的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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"的未定义引用。
你能告诉我问题是什么吗? 谢谢!

我正在使用Win7 64bit + Eclipse Indigo + MinGW


其他答案涵盖了大部分内容,但是存在几个问题。首先,getline()不在C标准库中,而是POSIX 2008扩展。通常,它将与POSIX兼容的编译器一起使用,因为_POSIX_C_SOURCE宏将使用适当的值进行定义。在getline()标准化之前,您可能具有较旧的编译器,在这种情况下,这是GNU扩展,并且在#include 之前必须在#define _GNU_SOURCE之前启用它,并且必须使用与GNU兼容的编译器,例如gcc 。

此外,nbytes应该具有类型size_t,而不是int。至少在我的系统上,它们的大小不同,size_t更长,并且使用int*而不是size_t*可能会带来严重的后果(并且也不使用默认的gcc设置进行编译)。有关详细信息,请参见getline手册页(http://linux.die.net/man/3/getline)。

做出更改后,您的程序可以在我的系统上编译并正常运行。


我也在使用MinGW。我检查了MinGW头文件,并且getline()没有出现在任何C头文件中,它仅出现在C ++头文件中。这意味着MinGW中不存在C函数getline()


getline不是标准功能,根据我的手册页,您需要设置一个功能测试宏才能使用它,

1
_POSIX_C_SOURCE >= 200809L || _XOPEN_SOURCE >= 700

对于glibc 2.10或更高版本,

1
_GNU_SOURCE

在那之前。