首页 > 解决方案 > 使用#define _GNU_SOURCE 后未定义对“XXX”的引用

问题描述

我用于search.h我的 c 程序,我需要将其放在#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

标签: cpostgresqlposixgnuundefined-reference

解决方案


在命令行末尾指定库

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

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


推荐阅读