要使用 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 標頭檔的安裝目錄。(在某些情況下,編譯器預設會查找相關目錄,因此您可以省略此選項。)例如,您的編譯命令列可能如下所示目錄
cc -c -I/usr/local/pgsql/include testprog.c
如果您正在使用 makefile,則將該選項新增到 CPPFLAGS
變數
CPPFLAGS += -I/usr/local/pgsql/include
如果您的程式有可能被其他使用者編譯,則不應像這樣硬式編碼目錄位置。相反,您可以執行工具 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 程式庫所在的目錄。(同樣,編譯器預設會搜尋某些目錄。)為了獲得最大的可移植性,請將 目錄
-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
選項或未指定正確的目錄。
如果您在文件中發現任何不正確、與您使用特定功能的經驗不符或需要進一步澄清的地方,請使用此表單來回報文件問題。