要构建(即编译和链接)使用 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
$
pkg-config --cflags libpq-I/usr/local/include
请注意,这已在路径前面包含 -I
。
未向编译器指定正确的选项将导致类似于以下内容的错误消息
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
或者再次使用 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
选项,或未指定正确的目录。