VastbaseG100

基于openGauss内核开发的企业级关系型数据库。

Menu

编译LibPQ程序

要编译(即编译并且链接)一个使用libpq的程序,需要经过以下步骤:

1、包含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)

2、通过为编译器提供 -Idirectory 选项,向编译器指出Vastbase G100头文件安装在哪里(在某些情况下编译器默认将查看该目录,因此可以忽略这个选项)。例如你的编译命令行形如:

cc -c -I/usr/local/vastbase/include testprog.c

3、如果你在使用 makefile,那么把该选项加到CPPFLAGS变量中:

CPPFLAGS += -I/usr/local/vastbase/include

4、如果程序可能由其他用户编译,那么则不应该像那样硬编码目录位置。可以运行工具pg_config在本地系统上找出头文件在哪里:

$ pg_config --includedir
/usr/local/include

无法为编译器指定正确的选项将导致一个错误消息,例如:

testlibpq.c:8:22: libpq-fe.h: No such file or directory

6、当链接最终的程序时,指定选项-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

指出这一部分问题的错误消息形如:

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