| PostgreSQL 7.4 文檔 | ||||
|---|---|---|---|---|
| Prev | Fast Backward | Chapter 27. libpq - C 庫 | Fast Forward | Next |
要制作(也就是說編譯和鏈接)你的 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)
告訴你的編譯器PostgreSQL頭文件的安裝位置, 方法是給你的編譯器提供 -Idirectory 選項。 (有些時候編譯器會查找缺省的目錄,因此你可以忽略這些選項。) 比如,你的命令行看起來象︰
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
如果沒能給編譯器提供正確的選項將產生類似下面這樣的錯誤信息
testlibpq.c:8:22: libpq-fe.h: No such file or directory
在鏈接最後的程序的時候,聲明選項 -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
這意味著你忘記這-L 或者沒有聲明正確的目錄。
如果你的代碼引用了頭文件 libpq-int.h, 而且你不原意修補你的代碼以避免使用它,那麼從 PostgreSQL7.2 開始, 該文件將在 includedir/postgresql/internal/libpq-int.h 裡出現, 因此你需要給你的編譯器命令行增加合適的 -I 選項。