【问题标题】:undefined reference to `readline' [duplicate]未定义对“readline”的引用[重复]
【发布时间】:2013-02-08 13:15:52
【问题描述】:

我在尝试运行 GNU Readline 库示例代码 available in wikipedia 时遇到问题。就是这样:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <readline/readline.h>
#include <readline/history.h>

int main()
{
    char* input, shell_prompt[100];

    // Configure readline to auto-complete paths when the tab key is hit.
    rl_bind_key('\t', rl_complete);

    for(;;) {
        // Create prompt string from user name and current working directory.
        snprintf(shell_prompt, sizeof(shell_prompt), "%s:%s $ ", getenv("USER"), getcwd(NULL, 1024));

        // Display prompt and read input (n.b. input must be freed after use)...
        input = readline(shell_prompt);

        // Check for EOF.
        if (!input)
            break;

        // Add input to history.
        add_history(input);

        // Do stuff...

        // Free input.
        free(input);
    }
}

我在受限环境中工作,readline 不可用,所以我必须下载源代码,编译并将其安装到我的主目录。

这是我的主目录中的结构:

.local
├── include
│   └── readline
│       ├── chardefs.h
│       ├── history.h
│       ├── keymaps.h
│       ├── readline.h
│       ├── rlconf.h
│       ├── rlstdc.h
│       ├── rltypedefs.h
│       └── tilde.h
└── lib
    ├── libhistory.a
    ├── libhistory.so -> libhistory.so.6
    ├── libhistory.so.6 -> libhistory.so.6.2
    ├── libhistory.so.6.2
    ├── libreadline.a
    ├── libreadline.so -> libreadline.so.6
    ├── libreadline.so.6 -> libreadline.so.6.2
    └── libreadline.so.6.2

问题是,当我调用 gcc 时,它会抛出一个错误:

$ gcc hello.c -o hello_c.o -I /home/my-home-dir/.local/include
/tmp/cckC236E.o: In function `main':
hello.c:(.text+0xa): undefined reference to `rl_complete'
hello.c:(.text+0x14): undefined reference to `rl_bind_key'
hello.c:(.text+0x60): undefined reference to `readline'
hello.c:(.text+0x77): undefined reference to `add_history'
collect2: error: ld returned 1 exit status

关于这个here 有一个答案,但我没有使用 Netbeans,我不太确定如何在命令行上指定库的路径。

我试图告诉链接器库在哪里,但结果还是一样:

$ gcc hello.c -o hello_c.o -I /home/my-home-dir/.local/include -Xlinker "-L /home/my-home-dir/.local/lib"
/tmp/cceiePMr.o: In function `main':
hello.c:(.text+0xa): undefined reference to `rl_complete'
hello.c:(.text+0x14): undefined reference to `rl_bind_key'
hello.c:(.text+0x60): undefined reference to `readline'
hello.c:(.text+0x77): undefined reference to `add_history'
collect2: error: ld returned 1 exit status

有什么我可能在这里遗漏的想法吗?

【问题讨论】:

  • 你需要链接库,所以把-lreadline放在你的gcc命令的末尾附近(之前可能还有-L.local/lib)。并从*.c 中获得*.o 使用gcc -Wall -c -g hello.c -o hello.o
  • 对 readline 和 add_history 使用 -ledit

标签: c readline libreadline


【解决方案1】:

您需要在 gcc 参数中使用 -lreadline 链接到实际库。

【讨论】:

    猜你喜欢
    • 2016-05-25
    • 2015-02-14
    • 1970-01-01
    • 2019-06-20
    • 2011-07-27
    • 2013-06-20
    • 2012-02-05
    • 2014-12-27
    • 2012-11-15
    相关资源
    最近更新 更多