pgsql.cc 提供对 postgresql.org 官网内容的中文翻译,由 Pigsty 团队维护。
要构建(即编译和链接)一个使用 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)
向编译器提供 -I 选项,指定 PostgreSQL 头文件的安装目录。(某些情况下,编译器默认会搜索该目录,此时可以省略这个选项。)例如,编译命令行可以是:directory
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
未向编译器指定正确的选项将导致类似以下内容的错误消息:
testlibpq.c:8:22: libpq-fe.h: No such file or directory
链接最终程序时,指定 -lpq 选项以链接 libpq 库,同时指定 -L 选项,告知编译器 libpq 库所在的目录。(同样,编译器默认会搜索某些目录。)为获得最大的可移植性,请将 directory-L 选项放在 -lpq 选项之前。例如:
cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq
你也可以使用pg_config找出库目录:
$pg_config --libdir/usr/local/pgsql/lib
指出这一部分问题的错误消息可能看起来像:
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选项或者没有指定正确的目录。
译文有误、术语不当或页面显示问题,请到译文仓库 pgsty/pgdoc 报告译文问题。 英文原文本身的问题,请在当前版本的对应页面向上游反馈;上游不再修订已结束维护的版本。