2011-03-14 93 views
2

我想在我的Mac上運行PostgreSQL。 PostgreQL本身工作正常,我可以創建數據庫和表之類的東西,但是當我嘗試用C++的東西,如連接到PostgreSQL:無法使用C++連接到PostgreSQL

#include <stdio.h> 
#include </Library/PostgreSQL/8.4/include/libpq-fe.h> 
#include <string> 

int  main() { 
PGconn   *conn; 
PGresult  *res; 
int    rec_count; 

conn = PQconnectdb("dbname=ljdata host=localhost user=dataman); 

if (PQstatus(conn) == CONNECTION_BAD) { 
puts("We were unable to connect to the database"); 
exit(0); 
} 

res = PQexec(conn, "update people set phonenumber=\'5055559999\' where id=3"); 

並且用類似編譯:

g++ -lpq db.cpp -o db 

我得到的錯誤 LD:庫找不到-lpq

,如果我沒有編譯LPQ,我得到

Undefined symbols: 
    "_PQclear", referenced from: 
     _main in ccpjNCAU.o 
     _main in ccpjNCAU.o" 

我已經包含libpq-fe.h,它不應該工作嗎?有人知道出了什麼問題嗎?

回答

4

g ++找不到pq庫。您必須指定在哪裏尋找它,用資本-L

g++ -L/path/to/pq/lib -lpq db.cpp -o db 

其中pq是/path/to/pq/lib/libpq.a(或任何擴展)

這裏是你可能想要這樣做:

  1. 改變包含線沒有路徑。

    #include "libpq-fe.h" 
    
  2. 添加包括路徑命令行

    g++ -I/Library/PostgreSQL/8.4/include db.cpp 
    
  3. 建立中介目標文件

    g++ -I/Library/PostgreSQL/8.4/include db.cpp -c -o db.o 
    
  4. 鏈接一起作爲一個單獨的步驟

    g++ -L/Library/PostgreSQL/8.4/lib db.o -lpq 
    
  5. 建立與使用-g

把它放在一起,兩個獨立的構建步驟調試信息:編譯和鏈接:

g++ -I/Library/PostgreSQL/8.4/include db.cpp -c -g -o db.o 
g++ -L/Library/PostgreSQL/8.4/lib db.o -lpq -o db 
+0

因此,如果我的文件在家裏,我應該只做g ++ -L/Library/PostgreSQL/8.4/include/libpq-fe.h?那也行不通。 – Confused 2011-03-14 22:34:24

+0

-L/path/to/lib/dir not/path/to/header/file。 libpq位於何處? – Tim 2011-03-14 22:39:52

+0

libpq-fe.h和libpq-events.h位於Library/PostgreSQL/8.4/include /中,但在Library/PostgreSQL/8.4/include/libpq – Confused 2011-03-14 22:46:46

0

libpq-fe.h是用戶庫,而不是一個系統庫,因此,你應該使用"..."代替<...>,像這樣:

#include "/Library/PostgreSQL/8.4/include/libpq-fe.h" 

看看this link。並確保libpq-fe.h實際上可以由您的編譯器找到。

+0

我想我的編譯器可以找到libpq-fe.h。將#include「/Library/PostgreSQL/8.4/include/libpq-fe.h」更改爲#include「Library/PostgreSQL/8.4/include/libpq-fe.h」後,出現錯誤:'PGconn'未聲明在此範圍內 錯誤:'conn'未在此範圍內聲明。由於PGconn已被定義,這不是說編譯器能找到libpq-fe.h嗎? – Confused 2011-03-14 22:31:10

0

有同樣的問題,你需要添加庫的路徑/etc/ld.so.conf,做到這一點,你會看到。 祝你好運