要构建 (即编译和链接) 一个使用 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 testlibpq.c
如果你的程序有可能被其他用户编译,
那么你不应当像那样硬编码目录位置。
作为替代,
你可以运行工具
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
选项,
或者没有指定正确的目录。