## 34.21.构建libpq程序 [](<>) 要使用libpq构建(即编译和链接)程序,您需要执行以下所有操作: - 包括`libpq-fe。H`头文件: ``` #include ``` 如果您未能做到这一点,那么您通常会从编译器中收到类似以下内容的错误消息: ``` 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) ``` - 通过提供`-我*`目录`*`选项添加到编译器中。(在某些情况下,编译器会在默认情况下查看相关目录,因此您可以忽略此选项。)例如,compile命令行可能如下所示: ``` cc -c -I/usr/local/pgsql/include testprog.c ``` 如果您使用的是makefiles,那么将该选项添加到`CPPFLAGS`变量: ``` CPPFLAGS += -I/usr/local/pgsql/include ``` 如果你的程序有可能被其他用户编译,那么你不应该像这样硬编码目录位置。相反,您可以运行该实用程序`pg_配置`[](<>)要了解头文件在本地系统上的位置,请执行以下操作: ``` $ pg_config --includedir /usr/local/include ``` 如果你有`包装配置`[](<>)安装后,您可以改为运行: ``` $ pkg-config --cflags libpq -I/usr/local/include ``` 请注意,这已经包括`-我`在小路前面。 未能为编译器指定正确的选项将导致错误消息,例如: ``` testlibpq.c:8:22: libpq-fe.h: No such file or directory ``` - 链接最终程序时,请指定选项`-lpq`这样libpq库和选项`-L*`目录`*`将编译器指向libpq库所在的目录。(同样,默认情况下,编译器将搜索一些目录。)为了实现最大的可移植性,请将`-L`选择权`-lpq`选项例如: ``` cc -o testprog testprog1.o testprog2.o -L/usr/local/pgsql/lib -lpq ``` 您可以使用`pg_配置`也: ``` $ pg_config --libdir /usr/local/pgsql/lib ``` 或者再次使用`包装配置`: ``` $ 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`选项或未指定正确的目录。