W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
要編譯(即編譯并且鏈接)一個使用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頭文件安裝在哪里(在某些情況下編譯器默認(rèn)將查看該目錄,因此你可以忽略這個選項)。例如你的編譯命令行可能看起來像:directory
cc -c -I/usr/local/pgsql/include testprog.c
如果你在使用 makefile,那么把該選項加到CPPFLAGS
變量中:
CPPFLAGS += -I/usr/local/pgsql/include
如果你的程序可能由其他用戶編譯,那么你不應(yīng)該像那樣硬編碼目錄位置。你可以運行工具pg_config
在本地系統(tǒng)上找出頭文件在哪里:
$
pg_config --includedir
/usr/local/include
$
pkg-config --cflags libpq
-I/usr/local/include
注意這將在路徑前面包括-I
。
無法為編譯器指定正確的選項將導(dǎo)致一個錯誤消息,例如:
testlibpq.c:8:22: libpq-fe.h: No such file or directory
當(dāng)鏈接最終的程序時,指定選項-lpq
,這樣libpq庫會被編譯進去,也可以用選項-L
向編譯器指出libpq庫所在的位置(再次,編譯器將默認(rèn)搜索某些目錄)。為了最大的可移植性,將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'
This means you forgot -lpq
.
/usr/bin/ld: cannot find -lpq
這意味著你忘記了-L
選項或者沒有指定正確的目錄。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: