27.13. 构建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选项,或者没有指定正确的目录。
如果你的代码引用了头文件libpq-int.h,而你拒绝修改代码使其不再使用它,那么从PostgreSQL 7.2 开始,这个文件位于,因此你需要在编译器命令行中加入适当的includedir/postgresql/internal/libpq-int.h-I选项。