历史版本。 PostgreSQL 9.1 已结束支持。 2016-10-27. 请参阅 当前版本手册.
31.19. 构建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)
向编译器提供
-I选项,指定 PostgreSQL 头文件的安装目录。(某些情况下,编译器默认会搜索该目录,此时可以省略这个选项。)例如,编译命令行可以是:directorycc -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选项或者没有指定正确的目录。