【问题标题】:getline not declared in this scope despite importing stdio尽管导入了 stdio,但 getline 未在此范围内声明
【发布时间】:2013-12-18 14:20:52
【问题描述】:

我需要在 C 中使用getline(),但是当我写的时候:

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

int main(int argc, char** argv) {

  char *line;
  getline(&line, NULL, stdin);
  free(line);

  return (0);
}

编译器写error: getline was not declared in this scope 我能做什么? getline 不是在stdio.h 中声明的吗?我以前从来没有遇到过这种问题。

我使用 GCC GNU 编译器。

【问题讨论】:

  • 不是来自 std 的 getline 吗?试试std::getline。另外,getline 声明在#include &lt;string&gt;.
  • 错误:getline 不是 std 的成员
  • @wendelbsilva; getline 的标头是 &lt;stdio.h&gt;。
  • @wendelbsilva 这是一个 C 问题而不是 C++。
  • 我看到您的问题已被多次编辑。您现在使用gcc 为我编译的代码没有错误,没有其他选项。顺便说一句,如果std::getline 导致错误“getline 不是 std 的成员”,那么您将代码编译为 C++。使用 C 编译器编译 C。(使用 gcc,而不是 g++,并使用 .c 后缀命名您的源文件。)

标签: c getline stdio


【解决方案1】:

您需要定义_GNU_SOURCE 才能使用此函数,要么在包含stdio.h 之前定义它,要么将其作为-D_GNU_SOURCE 传递给编译器,因为这是一个GNU 扩展函数。

另一个可能的原因是你的GLIBC没有这个功能,所以要么试试:

  • 在/usr/include/stdio.h 中寻找它

  • 如手册页所述测试_POSIX_C_SOURCE &gt;= 200809L || _XOPEN_SOURCE &gt;= 700(包括features.h)

以下实现可能工作(未经测试):

#define INTIAIL_SIZE 100
size_t getline(char **lineptr, size_t *n, FILE *stream)
{
    char c;
    size_t read = 0;
    char *tmp;

    if (!*lineptr) {
        if (!n)
            *n = INTIAIL_SIZE;

        tmp = malloc(*n);
        *lineptr = tmp;
    } else
        tmp = *lineptr;

    while ((c = fgetc(stream)) != '\n') {
        *tmp++ = c;

        if (++read >= *n) {
            char *r = realloc(tmp, *n * 2);
            if (!r) {
                errno = ENOMEM;
                return -1;
            } else
                tmp = r;
        }
    }

    *n = read;
    return read;
}

您当前遇到的错误:

  • line 使用后并没有释放它

  • 您没有通过引用传递line,因为函数原型是:ssize_t getline(char **lineptr, size_t *n, FILE *stream); 因此char **lineptr

【讨论】:

  • Free line after using it: OK,但是释放一些内存并不能解决函数没有声明的问题。
  • 包括 features.h 也会产生编译错误:没有这样的文件或目录
  • 另外,free 是在 stdlib.h 中定义的,所以一定要包含它。
  • 什么是greeping函数?
  • 正在搜索它,如果你在 Linux 系统上使用这个grep "getline" /usr/include/stdio.h
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-03
  • 2021-09-20
  • 2016-08-09
相关资源
最近更新 更多