↑↓ 选择↵ 打开⌫ 切换范围完整搜索

PG.CENTER 连接 PostgreSQL 文档、百科与生态知识。由 Pigsty 维护。

支持中的版本: 当前版本 (18) / 17 / 16 / 15 / 14
开发中的版本: 19 / 20devel
已结束支持的版本: 13 / 12 / 11 / 10 / 9.6 / 9.5 / 9.4 / 9.3 / 9.2 / 9.1 / 9.0 / 8.4 / 8.3 / 8.2 / 8.1 / 8.0 / 7.4 / 7.3 / 7.2
历史版本。 PostgreSQL 11 已结束支持。 2023-11-09. 请参阅 当前版本手册.

34.20. 构建 libpq 程序 #

要构建(即编译和链接)一个使用 libpq 的程序,需要完成以下所有步骤:

  • 包含 libpq-fe.h 头文件:

    #include <libpq-fe.h>
    

    如果没有这样做,编译器通常会给出类似以下内容的错误消息:

    foo.c: In function `main':
    foo.c:34: `PGconn' undeclared (first use in this function)
    foo.c:35: `PGresult' undeclared (first use in this function)
    foo.c:54: `CONNECTION_BAD' undeclared (first use in this function)
    foo.c:68: `PGRES_COMMAND_OK' undeclared (first use in this function)
    foo.c:95: `PGRES_TUPLES_OK' undeclared (first use in this function)
    

  • 向编译器提供 -Idirectory 选项,指定 PostgreSQL 头文件的安装目录。(某些情况下,编译器默认会搜索该目录,此时可以省略这个选项。)例如,编译命令行可以是:

    cc -c -I/usr/local/pgsql/include testprog.c
    

    如果使用 makefile,请将该选项添加到 CPPFLAGS 变量中:

    CPPFLAGS += -I/usr/local/pgsql/include
    

    如果你的程序可能由其他用户编译,那么你不应该像那样硬编码目录位置。你可以运行工具 pg_config 在本地系统上找出头文件在哪里:

    $ pg_config --includedir
    /usr/local/include
    

    如果你安装了 pkg-config,你可以运行:

    $ pkg-config --cflags libpq
    -I/usr/local/include
    

    注意这将在路径前面包括 -I。

    未向编译器指定正确的选项将导致类似以下内容的错误消息:

    testlibpq.c:8:22: libpq-fe.h: No such file or directory
    

  • 链接最终程序时,指定 -lpq 选项以链接 libpq 库,同时指定 -Ldirectory 选项,告知编译器 libpq 库所在的目录。(同样,编译器默认会搜索某些目录。)为获得最大的可移植性,请将 -L 选项放在 -lpq 选项之前。例如:

    cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
    

    你也可以使用 pg_config 找出库目录:

    $ pg_config --libdir
    /usr/local/pgsql/lib
    

    或者再次使用 pkg-config:

    $ pkg-config --libs libpq
    -L/usr/local/pgsql/lib -lpq
    

    再次提示这会打印出全部的选项,而不仅仅是路径。

    指出这一部分问题的错误消息可能看起来像:

    testlibpq.o: In function `main':
    testlibpq.o(.text+0x60): undefined reference to `PQsetdbLogin'
    testlibpq.o(.text+0x71): undefined reference to `PQstatus'
    testlibpq.o(.text+0xa4): undefined reference to `PQerrorMessage'
    

    这意味着你忘记了 -lpq。

    /usr/bin/ld: cannot find -lpq
    

    这意味着你忘记了 -L 选项或者没有指定正确的目录。

报告文档问题

阅读 上游文档. 反馈更正前请先核对 当前版本手册.