【问题标题】:undefined reference to 'XXX' after using #define _GNU_SOURCE使用#define _GNU_SOURCE 后未定义对“XXX”的引用
【发布时间】:2021-11-11 09:44:52
【问题描述】:

我在我的 c 程序中使用了search.h,我需要将#define _GNU_SOURCE 放在第一行以引入多个哈希表。但在那之后,像undefined reference to 'log10' 和undefined reference to 'PQntuples' 这样的错误弹出。我当然需要那里的所有包,我现在应该如何编译程序?任何帮助将不胜感激!谢谢。

标题:

#define _GNU_SOURCE

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
#include <string.h>
// library for psql
#include <libpq-fe.h>
#include <unistd.h>
#include <time.h>
#include <search.h>

int main(void){
    char host[] = "localhost";
    char port[] = "5432";
    char db_name[] = "db_name";
    char user[] = "test_usr";
    char password[] = "123456";
    sprintf(db_str, "host=%s port=%s dbname=%s user=%s password=%s",
             host, port, db_name, user, password);
    PGconn *db_connection = DBConnect(db_str);

    struct hsearch_data htab;
    hcreate_r(10, &htb);
    ENTRY e, *ep;
    e.key = "test";
    e.data = (void *) 1;
    hsearch_r(e, ENTER, &ep, &htab);
}

这就是我编译文件的方式:

gcc -Wall -Wextra -I/home/userX/postgresql/include -L/home/userX/postgresql/lib -lm -lpq -g my_program.c

【问题讨论】:

标签: c postgresql posix gnu undefined-reference


【解决方案1】:

在命令行末尾指定库

gcc -Wall -Wextra -I/home/userX/postgresql/include \
      -L/home/userX/postgresql/lib -g my_program.c -lpq -lm
//                                                 ^^^^^^^^

gcc 在命令行上从左到右查看所需的符号。
对于源文件之前的库,当 gcc 处理 -llib 参数时,它没有任何要求,因此不会从库中“提取”任何函数。

【讨论】:

  • Alt: ... $(pkg-config --cflags --libs libpq) -lm
  • @heisthere 而且您通常应该将最“低级”的库放在最后。 m(数学库)非常低级,pq 可能会使用其中的东西,所以 pq 应该放在 m 之前。
  • 感谢@TedLyngmo...这也是因为 gcc 处理库的方式。如果您说-lm -lpq 并且 pq 需要数学库中的某些内容,它将不会被“提取”。
  • 免责声明我不知道其他编译器/链接器如何处理它。我只是总是最后说-lwhatever,它有效:-)
  • @thebusybee ... 除非使用“外循环”链接器选项-Wl,--start-group 具有循环依赖关系的库 -Wl,--end-group。 :-)
猜你喜欢
  • 2011-12-01
  • 1970-01-01
  • 2020-02-11
  • 2010-11-08
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多