On this page
33.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
如果您的程序有可能被其他用户编译,则您不应像这样对目录位置进行硬编码。相反,您可以运行 Utilpg_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 库,并指定选项-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
选项或未指定正确的目录。