开发者

Cannot connect to PostgreSQL using C++

开发者 https://www.devze.com 2023-02-17 00:00 出处:网络
I am trying to run PostgreSQL on my mac. PostgreQL itself works fine and I can create database and table and stuff but when I try to connect to PostgreSQL using C++ with something like:

I am trying to run PostgreSQL on my mac. PostgreQL itself works fine and I can create database and table and stuff but when I try to connect to PostgreSQL using C++ with something like:

#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");

and compile with something like:

g++ -lpq db.cpp -o db

I get the error ld: library not found for -lpq

and if I compile without lpq, I get

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

I have already 开发者_运维技巧included the libpq-fe.h, shouldn't it work? Does anybody know what went wrong?


g++ can't find the pq library. You have to specify where to look for it, with a capital -L:

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

where pq is /path/to/pq/lib/libpq.a (or whatever the extension is)

Here's what you probably want to do:

  1. change the include line to not have the path.

    #include "libpq-fe.h"
    
  2. Add the include path to the commandline

    g++ -I/Library/PostgreSQL/8.4/include db.cpp
    
  3. Build intermediary object files

    g++ -I/Library/PostgreSQL/8.4/include db.cpp -c -o db.o
    
  4. Link it together as a separate step

    g++ -L/Library/PostgreSQL/8.4/lib db.o -lpq
    
  5. Build with debug info using -g

Put it all together, for two separate build steps: compile and link:

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


libpq-fe.h is a user library, not a system library, and therefore you should use "..." instead of <...>, like this:

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

Take a look at this link. And make sure libpq-fe.h can actually be found by your compiler.


Had the same problem, You need to add the path of the library to /etc/ld.so.conf, do it and you'll see. Good luck

0

精彩评论

暂无评论...
验证码 换一张
取 消